我正在使用[Repository& UOW]模式与EF Core一起使用。
问题
大多数情况下,在每个成功呼叫上下文被处理之后抛出错误。
扩展方法
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>>();
}
配置服务
//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));
}
}
答案 0 :(得分:3)