'How to use DBContextFactory in Generic Repository
My current application has three layers: Web, Infrastructure and Core. Generic Repository is in Infrasturcture layer and works fine with DBContext. After I switch to DBContextFactory, service can't start and system can out error:Error while validating the service descriptor 'ServiceType: Core.ServiceInterfaces.IBasCityService Lifetime: Scoped ImplementationType: Core.Services.BasCityService': Unable to resolve service for type 'Core.Interfaces.IGenericRepository`1[Core.Entities.BasCity]' while attempting to activate 'Core.Services.BasCityService' Generic Repository Class
public class GenericRepository<T> : IGenericRepository<T> where T : class
 {
 
        protected readonly IDbContextFactory<DbContext> _DbFactory;
        public GenericRepository(IDbContextFactory<DbContext> DbFactory)
        {
            _DbFactory = DbFactory;
        }
        public virtual async Task<T> GetByIdAsync(int id)
        {
            using var _dbContext = _DbFactory.CreateDbContext();
            if (_dbContext is not null)
                return await _dbContext.Set<T>().FindAsync(id);                        
            else
                return null;
        }
       .......
}
Service Class which is in Core layer
public class BasCityService : IBasCityService, IDisposable
  {
        private readonly IGenericRepository<BasCity> _cityRepository;
        private readonly ISysExceptionLogService _exceptionLogService;
   
        public BasCityService(IGenericRepository<BasCity> cityRepository,  
         ISysExceptionLogService exceptionLogService)
        {
            _cityRepository = cityRepository;
            _exceptionLogService = exceptionLogService;
        }
        public async Task<BasCity> GetByIdAsync(int id)
        {
            try
            {
                return await _cityRepository.GetByIdAsync(id);
            }
            catch(Exception ex)
            {
                await _exceptionLogService?.CreateLogAsync(ex, null, 
                    "BasCityService.GetByIdAsync()");
                return null;
            }
          
        }
  .........
}
if I inject DbContext instead of DBContextFactory in Generic Repository constructor or directly inject IDbContextFactory DbFactory in service constructor, everthing is fine. Is there any way I can use DBFactory in the Generic Repository instead of injecting DBFactory in service constructor? I want to keep my generic repository class. Thanks for your help
Solution 1:[1]
for this to work you need to setup something like builder.Services.AddTransient<IGenericRepository, GenericRepository>(); as it is a parameter of your constructor. – Brian Parker
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Frank | 
