Pooria Sadeghy
Pooria Sadeghy

Reputation: 443

Cannot consume scoped service MyDbContext from singleton - InvalidOperationException

My project is .net core 2 base, i set context and repository in startup.cs file

services.AddDbContext<DocumentContext>(options => options.UseSqlServer(connection));
services.AddSingleton<IAuthRepository, AuthRepository>();

IAuthRepository file :

public interface IAuthRepository
{
    int Login(LoginRequest model);
    int Register(RegisterRequest model);
}

AuthRepository file :

private readonly DocumentContext db;
public AuthRepository(DocumentContext context)
{
    this.db = context;
}
...

Controller:

private IAuthRepository AuthMethod { get; set; }
public AuthController(IAuthRepository authMethod)
{
    this.AuthMethod = authMethod;
}

I get this error

InvalidOperationException: Cannot consume scoped service '...DocumentContext' from singleton '...IAuthRepository'.

Upvotes: 3

Views: 7896

Answers (1)

Barr J
Barr J

Reputation: 10927

Well, this is pretty common to trip over in asp.net core, and there is a full article about it in dotnetcoretutorials:

...because it’s actually the Service DI of ASP.net Core trying to make sure you don’t trip yourself up. Although it’s not foolproof (They still give you enough rope to hang yourself), it’s actually trying to stop you making a classic DI scope mistake.

the conclusion at the end of it all is simple: because the ChildService is scoped, but the FatherService is singleton, it’s not going to allow us to run:

...is that transient is “everytime this service is requested, create a new instance”, so technically this is correct behaviour (Even though it’s likely to cause issues). Whereas a “scoped” instance in ASP.net Core is “a new instance per page request” which cannot be fulfilled when the parent is singleton.

Upvotes: 5

Related Questions