.NET Core IServiceScopeFactory.CreateScope()与IServiceProvider.CreateScope()扩展 [英] .NET Core IServiceScopeFactory.CreateScope() vs IServiceProvider.CreateScope() extension

查看:1443
本文介绍了.NET Core IServiceScopeFactory.CreateScope()与IServiceProvider.CreateScope()扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,使用内置的依赖项注入时,.NET Core控制台应用程序将需要您自己创建和管理所有范围,而ASP.NET Core应用程序将创建和管理默认情况下,通过定义的中间件实现HttpRequest 范围。

My understanding is that when using the built in the dependency injection, a .NET Core console app will require you to create and manage all scopes yourself whereas a ASP.NET Core app will create and manage the HttpRequest scope by default through defined middleware(s).

使用ASP.NET Core,您可以选择通过调用 CreateScope()创建和管理自己的范围当您需要位于 HttpRequest 之外的服务时。

With ASP.NET Core, you can optionally create and manage your own scopes that by calling CreateScope() for when you need services that live outside of a HttpRequest.

很明显,调用 IServiceScopeFactory.CreateScope()每次都会创建一个新的 IServiceScope ;但是,是否每次都调用 IServiceProvider.CreateScope()扩展方法还会创建一个新的 IServiceScope 吗?

It is clear that calling IServiceScopeFactory.CreateScope() will create a new IServiceScope every time; however, does calling the IServiceProvider.CreateScope() extension method also create a new IServiceScope every time?

基本上,以下两种在ASP.NET Core和.NET Core控制台应用程序中创建作用域的方法之间存在有意义的区别:

Basically, is there a meaningful difference between the following ways to create scope in both ASP.NET Core and .NET Core console apps:

public class Foo()
{
    public Foo(IServiceProvider serviceProvider)
    {
        using(var scope = serviceProvider.CreateScope())
        {   
            scope.ServiceProvider.GetServices<>();           
        }
    }
}

public class Bar()
{
    public Bar(IServiceScopeFactory scopeFactory)
    {
        using(var scope = scopeFactory.CreateScope())
        {   
            scope.ServiceProvider.GetServices<>();           
        }
    }
}


推荐答案

从IServiceProvider创建范围解决 IServiceScopeFactory 并对其调用 CreateScope()

public static IServiceScope CreateScope(this IServiceProvider provider)
{
    return provider.GetRequiredService<IServiceScopeFactory>().CreateScope();
}

所以,就像@Evk


在功能上,两种方法是相同的

functionally both methods are identical

IServiceProvider 刚刚包装的调用 CreateScope() IServiceScopeFactory

这篇关于.NET Core IServiceScopeFactory.CreateScope()与IServiceProvider.CreateScope()扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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