I have created a asp .net core mvc on an ASP.NetNET Core 8.0, MVC app.
Here, I created AppDbContext is my AppDbContext
class:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<User> Users { get; set; }
}
DbRepoDbRepo
class:
public class DbRepo
{
internal readonly AppDbContext db;
internal DbRepo(AppDbContext context)
{
this.db = context;
}
}
Here's a user repository where I need to use db contextDbContext
, there could be multiple repositoryrepositories:
public class UserRepository : DbRepo, IUser<User, User, string>
{
public async Task<bool> Create(User user)
{
try
{
if (!await IsExist(user))
{
await db.AddAsync(user);
}
return db.SaveChanges() > 0;
}
catch (Exception)
{
return false;
}
}
}
Here a class for DataAccessFactoryThis is the DataAccessFactory
class for loosely coupled dependencies:
public class DataAccessFactory
{
public static IUser<User, User, string> UserData()
{
return new UserRepository();
}
}
Now Serviceservice will call to the dataAccessfactoryDataAccessFactory
to repository methods:
public class UserService
{
public static Task<bool> CreateUser(UserDTO newUser)
{
User user = UserMapping(newUser);
return DataAccessFactory.UserData().Create(user);
}
}
And then this service will call from controller. Here is the problem, there should to give an argument for inherit DbRepoDbRepo
class for every repo.
How could I solve it.?
I added this in Program.csProgram.cs
:
builder.Services.AddScoped<DbRepo>();