本文介绍了.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,您可以选择创建和管理您自己的作用域,当您需要位于 HttpRequest 之外的服务时,您可以通过调用 CreateScope() 来创建和管理您自己的作用域.

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<>();           
        }
    }
}

推荐答案

CreateScope from IServiceProvider 解析 IServiceScopeFactory 并调用 CreateScope() :

CreateScope from IServiceProvider resolve IServiceScopeFactory and call CreateScope() on it:

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

所以,正如@Evk 所说

So, as said @Evk

功能上两种方法是相同的

IServiceProvider 刚刚包装了来自 IServiceScopeFactory

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

10-23 10:55