为什么我的作用域依赖项在单个作用域中实例化了两次?
Why is my scoped dependency instantiated twice in single scope?
假设我有一个 Singleton,它具有一个 Scoped 依赖项(并且永远由 Singleton 持有)。
然后我创建一个作用域并从容器中获取 Singleton 和 Scoped 实例。
我希望 Scoped 在单个范围内只实例化一次。
请查看简化的代码示例:
namespace TrivialConsole
{
using Microsoft.Extensions.DependencyInjection;
using System;
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddScoped<Scoped>();
services.AddSingleton<Singleton>();
var provider = services.BuildServiceProvider();
using (var rootScope = provider.CreateScope())
{
var scopeProvider = rootScope.ServiceProvider;
var singleton = scopeProvider.GetRequiredService<Singleton>();
var scoped = scopeProvider.GetRequiredService<Scoped>();
}
}
}
public class Singleton
{
private static int instances = 0;
private readonly Scoped scoped;
public Singleton(Scoped scoped)
{
instances += 1;
this.scoped = scoped;
Console.WriteLine($"singleton {instances}");
}
}
public class Scoped
{
private static int instances = 0;
public Scoped()
{
instances += 1;
Console.WriteLine($"scoped {instances}");
}
}
}
结果:
scoped 1
singleton 1
scoped 2
预期结果 ->
scoped 1
singleton 1
根据文档,在此框架中不应将作用域类型注入到单例中。
Do not resolve a scoped service from a singleton and be careful not to
do so indirectly, for example, through a transient service. It may
cause the service to have incorrect state when processing subsequent
requests. It's fine to:
- Resolve a singleton service from a scoped or transient service.
- Resolve a scoped service from another scoped or transient service.
假设我有一个 Singleton,它具有一个 Scoped 依赖项(并且永远由 Singleton 持有)。
然后我创建一个作用域并从容器中获取 Singleton 和 Scoped 实例。 我希望 Scoped 在单个范围内只实例化一次。
请查看简化的代码示例:
namespace TrivialConsole
{
using Microsoft.Extensions.DependencyInjection;
using System;
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddScoped<Scoped>();
services.AddSingleton<Singleton>();
var provider = services.BuildServiceProvider();
using (var rootScope = provider.CreateScope())
{
var scopeProvider = rootScope.ServiceProvider;
var singleton = scopeProvider.GetRequiredService<Singleton>();
var scoped = scopeProvider.GetRequiredService<Scoped>();
}
}
}
public class Singleton
{
private static int instances = 0;
private readonly Scoped scoped;
public Singleton(Scoped scoped)
{
instances += 1;
this.scoped = scoped;
Console.WriteLine($"singleton {instances}");
}
}
public class Scoped
{
private static int instances = 0;
public Scoped()
{
instances += 1;
Console.WriteLine($"scoped {instances}");
}
}
}
结果:
scoped 1
singleton 1
scoped 2
预期结果 ->
scoped 1
singleton 1
根据文档,在此框架中不应将作用域类型注入到单例中。
Do not resolve a scoped service from a singleton and be careful not to do so indirectly, for example, through a transient service. It may cause the service to have incorrect state when processing subsequent requests. It's fine to:
- Resolve a singleton service from a scoped or transient service.
- Resolve a scoped service from another scoped or transient service.