Shubhajyoti Ghosh Shubhajyoti Ghosh - 1 year ago 96
C# Question

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

}


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


}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download