如何在通用存储库中使用DBContextFactory



我目前的应用程序有三层:Web, Infrastructure和Core。通用存储库位于基础设施层,可以很好地与DBContext一起工作。在我切换到DBContextFactory后,服务无法启动,系统无法启动错误:在验证服务描述符"ServiceType: Core.ServiceInterfaces.IBasCityService Lifetime: Scoped ImplementationType: Core.Services"时出错。BasCityService':无法解析类型' core . interfaces . genericrepository '的服务。在尝试激活Core.Services.BasCityService时通用存储库类

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;

}
.......
}

内核层中的服务类

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;
}

}
.........
}

如果我在通用存储库构造函数中注入DbContext而不是DBContextFactory,或者直接在服务构造函数中注入IDbContextFactory DbFactory,一切都没问题。我是否可以在通用存储库中使用DBFactory,而不是在服务构造函数中注入DBFactory ?我想保留我的通用存储库类。谢谢你的帮助

要使其工作,您需要设置类似于builder.Services.AddTransient<genericrepository,>();因为它是构造函数的参数。- - - - - -布莱恩·帕克

相关内容

  • 没有找到相关文章

最新更新