解决单例时获取DbContext [英] Getting DbContext when resolving a singleton

查看:423
本文介绍了解决单例时获取DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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<MyContext>()会引发错误:

无法从根提供者解析作用域服务'MyContext'.

Cannot resolve scoped service 'MyContext' from root provider.

我该如何实现?我不想将MyDbContext注入到MyModel构造器中,因为它在一个没有理由了解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);
    }
});    

上面的代码创建了一个作用域 IServiceProvider,可用于获取作用域服务.

This code above creates a scoped IServiceProvider that can be used for obtaining scoped services.

这篇关于解决单例时获取DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆