无法使用来自单例的作用域服务 MyDbContext - InvalidOperationException
Cannot consume scoped service MyDbContext from singleton - InvalidOperationException
我的项目是 .net core 2 base,我在 startup.cs 文件
中设置了上下文和存储库
services.AddDbContext<DocumentContext>(options => options.UseSqlServer(connection));
services.AddSingleton<IAuthRepository, AuthRepository>();
IAuthRepository 文件:
public interface IAuthRepository
{
int Login(LoginRequest model);
int Register(RegisterRequest model);
}
AuthRepository 文件:
private readonly DocumentContext db;
public AuthRepository(DocumentContext context)
{
this.db = context;
}
...
控制器:
private IAuthRepository AuthMethod { get; set; }
public AuthController(IAuthRepository authMethod)
{
this.AuthMethod = authMethod;
}
我收到这个错误
InvalidOperationException: Cannot consume scoped service '...DocumentContext' from singleton '...IAuthRepository'.
嗯,这在 asp.net 核心中很常见,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.
最后的结论很简单:因为 ChildService 是作用域的,而 FatherService 是单例的,它不允许我们 运行 :
...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.
我的项目是 .net core 2 base,我在 startup.cs 文件
中设置了上下文和存储库services.AddDbContext<DocumentContext>(options => options.UseSqlServer(connection));
services.AddSingleton<IAuthRepository, AuthRepository>();
IAuthRepository 文件:
public interface IAuthRepository
{
int Login(LoginRequest model);
int Register(RegisterRequest model);
}
AuthRepository 文件:
private readonly DocumentContext db;
public AuthRepository(DocumentContext context)
{
this.db = context;
}
...
控制器:
private IAuthRepository AuthMethod { get; set; }
public AuthController(IAuthRepository authMethod)
{
this.AuthMethod = authMethod;
}
我收到这个错误
InvalidOperationException: Cannot consume scoped service '...DocumentContext' from singleton '...IAuthRepository'.
嗯,这在 asp.net 核心中很常见,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.
最后的结论很简单:因为 ChildService 是作用域的,而 FatherService 是单例的,它不允许我们 运行 :
...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.