我使用[库& UOW]模式与EF核心工作。为什么在EF核心中的每个API调用之后自动处理DbContext?
问题
大部分时间里,每一个成功的呼叫上下文配置&抛出错误之后。
扩展方法
public static IServiceCollection AddDataAccessConfig<C>(this IServiceCollection services) where C : DbContext
{
RegisterDataAccess<C>(services);
return services;
}
private static void RegisterDataAccess<C>(IServiceCollection services) where C : DbContext
{
services.TryAddScoped<IUnitOfWork<C>, UnitOfWork<C>>();
}
ConfigureServices
//Register Context
services.AddDataAccessConfig<MyDbContext>();
services.AddDbContext<MyDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DbCon"));
});
//Register Repository
services.TryAddScoped<IUserRepository, UserRepository>();
我曾尝试与娄代码。但没有运气
TryAddTransient
services.TryAddTransient<IUserRepository, UserRepository>();
库基地
protected RepositoryBase(IUnitOfWork<C> unitOfWork)
{
UnitOfWork = unitOfWork;
_dbSet = UnitOfWork.GetContext.Set<E>(); // THIS LINE THROW ERROR
}
UOW
public UnitOfWork(C dbcontext)
{
_dbContext = dbcontext;
}
public C GetContext
{
get { return _dbContext; }
}
样品呼叫服务
public IActionResult ByUser(string uid, string pwd)
{
var result = _userRepository.GetValidUser(uid, pwd);
if (string.IsNullOrEmpty(result))
{
return Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(result));
}
}
你是什么意思的“每一个电话后”?告诉我们这个代码,你有什么问题。 – DavidG
'使用[Repository&UOW]模式来处理EF Core' <=为什么? DbContext类型是一个UoW模式的实现,'DbSet类型是一个Repository模式的实现。为什么在你自己的相同模式实现中重新包装这些类型?你没有增加任何有价值的东西,只是增加了更多的代码和抽象,这使得很难阅读,调试和使用这些类型。 – Igor
@DavidG:我更新了我的帖子 –