gpt4 book ai didi

.net - 使用 Autofac LifeTimeScope 和 Asp.net Core DI Extension IServiceScopeFactory 创建范围之间的区别

转载 作者:行者123 更新时间:2023-12-04 18:01:50 25 4
gpt4 key购买 nike

我正在开发一个应用程序 Asp.net 核心 使用 Autofac 作为默认 DI,在我的集成测试中,我需要一些服务,在安装之前
我通过创建 IServiceScopeFactory 注入(inject)的 Autofac然后调用方法CreateScope()能够获得所需的服务,就像下面的代码:

public void ExampleOfAspNetServiceScope(){    
var scopeFactory = _testServer.Host.Services.GetRequiredService<IServiceScopeFactory>();

using (var scope = scopeFactory.CreateScope()){
var service = scope.ServiceProvider.GetService<ISomeService>();
// Some stuff...
}
}

将 Autofac 安装到我的应用程序后,我在文档中找到了接口(interface) ILifeTimeScope,现在我的代码可以重写如下:
public void ExampleOfAutofacScope(){    
var lifetimeScope = _testServer.Host.Services.GetRequiredService<ILifetimeScope>();

using (var scope = lifetimeScope.BeginLifetimeScope()){
var service = scope.Resolve<ISomeService>();
// Some stuff...
}
}

我对两者都进行了集成测试,它们的行为似乎相同。所以,我想知道这两种方法有什么区别。

提前致谢。

最佳答案

这是同一件事,只是使用 Microsoft.Extensions.DependencyInjection 抽象而不是直接使用 Autofac。

I'd recommend looking at the actual code in Autofac.Extensions.DependencyInjection for more concrete clarity.它实际上并不多,您可以自己确切地看到它是如何工作的。

关于.net - 使用 Autofac LifeTimeScope 和 Asp.net Core DI Extension IServiceScopeFactory 创建范围之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45446214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com