在ASP.NET Core中创建范围工厂 [英] Create scope factory in asp.net core

查看:112
本文介绍了在ASP.NET Core中创建范围工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在asp.net核心中创建作用域容器,并在我的singleton方法的2种方法中使用它。

I want to create scoped container in asp.net core and use it in 2 methods of my singleton method.

我尝试在sigleton的每种方法中创建此容器。

I've tried create this in each method of sigleton. it works, but i think it is overhead.

var scopeFactory = _serviceProvider.GetService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var scopedContainer = scope.ServiceProvider;

我在需要时用每种方法编写它。我认为这是逻辑错误。请给我解释一下如何正确执行?谢谢

I write it in each method when i need it. I think it is logic mistake. Please, explain me how to do it correct? thank you

推荐答案

从技术上讲,这不是错误的操作方式。如果您位于单例服务中,并且需要访问作用域服务,则应该创建一个新的服务范围,并从该范围的服务提供者那里检索服务。完成后,您还应该配置范围

It is technically not incorrect the way you do it. If you are within a singleton service and you need to access scoped services, then you should create a new service scope and retrieve the services from that scope’s service provider. And when you are done, you should also dispose the scope.

在实践中,您可以对此进行一些简化。您应该避免将 IServiceProvider 直接注入服务中。相反,您可以直接注入 IServiceScopeFactory 。然后,您还应该使用 using 语句创建作用域,以确保在使用后将其正确处置。

In practice, you can simplify this a bit. You should avoid having to inject IServiceProvider directly into a service. Instead, you can just inject the IServiceScopeFactory directly. And then you should also create the scope with a using statement to make sure that it is disposed properly after use.

因此,单例服务示例如下所示:

So an example singleton service could look like this:

public class ExampleSingletonService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public ExampleSingletonService(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public async Task DoSomethingAsync()
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            var db = scope.ServiceProvider.GetService<MyDbContext>();

            db.Add(new Foo());
            await db.SaveChangesAsync();
        }
    }
}

如您所见,确实不是很多 。但这当然会让您三思而后行,是否要在单个实例中使用作用域服务。

As you can see, there isn’t really that much overhead for this. But of course this makes you think twice about whether you want to use a scoped service within a singleton or not.

这篇关于在ASP.NET Core中创建范围工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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