AddScoped()如何在Asp.net核心之外运行?

时间:2017-08-12 18:26:04

标签: dependency-injection asp.net-core

假设我想在一个作为Azure Web作业运行的控制台应用程序中使用依赖注入。这样做我正在重用我的自定义服务注册方法" AddATonOfServices()"我在相关的Asp.net应用程序中使用它。

我的问题是,如何在" AddATonOfServices()"中注册的服务?使用AddScoped()现在在控制台应用程序中运行?他们表现得像Transient或Singleton,或者如何?会有任何意想不到的行为吗?

感谢。

1 个答案:

答案 0 :(得分:6)

如果您通过IServiceScopeFactory创建作用域,则会将其解析为作用域。

// provider is the root container
using(var scope = provider.GetService<IServiceScopeFactory>().CreateScope())
{
    var scopedService = scope.ServiceProvider.GetRequiredService<IScopedService>();
    // do something
}
// scope will be disposed and all scoped and transient services which implement IDisposable

如果您从根容器中解析范围服务,那么它将实际上是一个单例(假设provider只要应用程序存在就会生存)