简体   繁体   中英

Why DbContext autometically disposed after every api call in EF Core?

I am using [ Repository & UOW ] Pattern to work with EF Core.

Problem

Most of the time, after every single successfully call context is disposed & throw error.

Extension Method

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>();   

I have tried with bellow code. But no luck

TryAddTransient

services.TryAddTransient<IUserRepository, UserRepository>();

Repository Base

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

Sample Calling Service

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

Changing the lifetime of your IUserRepository will not affect the lifetime of the DbContext . There's an overload of AddDbContext that allows you to specify the lifetime of the DbContext . eg

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

The default ServiceLifetime.Scoped only really works well if you're inside an ASP.NET Core application. See here for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM