解析单例时获取 DbContext [英] Getting DbContext when resolving a singleton
问题描述
在 ConfigureServices
中我有
services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
以及
services.AddSingleton<IMyModel>(s =>
{
var dbContext = s.GetService<MyContext>();
var lastItem= dbContext.Items.LastOrDefault();
return new MyModel(lastItem);
});
但是 s.GetService
抛出一个错误:
But s.GetService<MyContext>()
throws an error:
无法从根提供程序解析范围服务MyContext".
Cannot resolve scoped service 'MyContext' from root provider.
我怎样才能做到这一点?我不想在 MyModel
构造函数中注入 MyDbContext
,因为它是在一个应该没有理由了解 Entity Framework
的库中.
How can I achieve that? I don't want to inject MyDbContext
in MyModel
contructor as it is in a library which should have no reason to know about Entity Framework
.
推荐答案
AddDbContext
默认使用 范围生活方式:
AddDbContext
defaults to using a scoped lifestyle:
范围生命周期服务(AddScoped)已创建每个客户端请求(连接)一次.
Scoped lifetime services (AddScoped) are created once per client request (connection).
抛出错误的原因是您试图从请求外部获取 MyContext
的实例.正如错误消息所暗示的那样,无法从根 IServiceProvider
获取 范围内 服务.
The reason an error is being thrown is that you're attempting to obtain an instance of MyContext
from outside of a request. As the error message suggests, it is not possible to obtain a scoped service from the root IServiceProvider
.
出于您的目的,您可以显式创建一个范围并将其用于您的依赖项解析,如下所示:
For your purposes, you can create a scope explicitly and use that for your dependency resolution, like so:
services.AddSingleton<IMyModel>(sp =>
{
using (var scope = sp.CreateScope())
{
var dbContext = scope.ServiceProvider.GetService<MyContext>();
var lastItem = dbContext.Items.LastOrDefault();
return new MyModel(lastItem);
}
});
上面的代码创建了一个 scoped IServiceProvider
可用于获取 scoped 服务.
This code above creates a scoped IServiceProvider
that can be used for obtaining scoped services.
这篇关于解析单例时获取 DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!