bilpor
bilpor

Reputation: 3889

.net core 2.0 scoping issue with dbcontext

In .Net core 1.0 and 1.1 in my Services Collection I had:

services.AddDbContext<VisualJobsDbContext>();
...
...
services.AddScoped<IRecruiterRepository, RecruiterRepository>();
services.AddSingleton<IAccountRepository, AccountRepository>();

this seemed to work. Now I've gone to .net core 2.0 this has stopped working:

I've changed the above to :

services.AddDbContext<VisualJobsDbContext>(ServiceLifetime.Scoped); 
... 
... 
services.AddScoped<IRecruiterRepository, RecruiterRepository>();
services.AddScoped<IAccountRepository, AccountRepository>();

I still receive the following error using swagger:

An unhandled exception occurred while processing the request. InvalidOperationException: Cannot consume scoped service FindaJobRepository.Interfaces.IAccountRepository from singleton FindaJobServices.Interfaces.IAccountService

Does anybody have any ideas what else I can do?

Upvotes: 0

Views: 489

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239260

Not sure how that ever worked, but essentially your issue is that you're trying to inject scoped services into a singleton, which based on the error is your AccountService.

Simply, if you need to use scoped services, the classes you inject them into must also be scoped. If you need the lifetime to be singleton, then your only option is use the service locator anti-pattern, where you instead inject IServiceProvider, and then create a scope around your operations:

using (var scope = _serviceProvider.CreateScope())
{
    var context = scope.GetRequiredService<MyDbContext>();
    // do something with context
}

Importantly, do not save the instances you retrieve from your scope to ivars, statics, etc. on your singleton class. These will disposed when the scope is disposed.

Upvotes: 0

IAccountService is a added as singleton and can't depend on a service with a shorter lifetime. IAccountRepository is a scoped service.

Probably you have a constructor with something like this:

public IAccountService(IAccountRepository accountRepository) {

}

Upvotes: 1

Related Questions