0

我使用[库& 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)); 
        } 


} 
+1

你是什么意思的“每一个电话后”?告诉我们这个代码,你有什么问题。 – DavidG

+5

'使用[Repository&UOW]模式来处理EF Core' <=为什么? DbContext类型是一个UoW模式的实现,'DbSet类型是一个Repository模式的实现。为什么在你自己的相同模式实现中重新包装这些类型?你没有增加任何有价值的东西,只是增加了更多的代码和抽象,这使得很难阅读,调试和使用这些类型。 – Igor

+0

@DavidG:我更新了我的帖子 –

回答

2

改变你的DbContext的寿命IUserRepository不会影响寿命。有overloadAddDbContext,允许您指定DbContext的生命周期。例如

services.AddDbContext<MyDbContext>(options => 
{ 
    options.UseSqlServer(Configuration.GetConnectionString("DbCon")); 
}, ServiceLifetime.Transient); 

默认ServiceLifetime.Scoped如果你是一个ASP.NET的核心应用内唯一真正行之有效。有关更多信息,请参阅here

+3

作为单例的db上下文将是一个非常糟糕的主意。 – DavidG

+0

@KirkLarkin:感谢您的解决方案。 –

+0

这究竟是如何解决问题的? –

相关问题