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

asp.net-core asp.net-core-webapi c# entity-framework-core repository-pattern

Question

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));
    }
}
1
0
7/11/2019 6:47:18 PM

Accepted Answer

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. e.g.

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.

3
8/17/2017 12:50:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow