//瞬时生命周期
ServiceCollection services = new ServiceCollection();
services.AddTransient<TestServiceImpl>();
using (ServiceProvider sp = services.BuildServiceProvider())
{
var ts1 = sp.GetRequiredService<TestServiceImpl>();
var ts2 = sp.GetRequiredService<TestServiceImpl>();
Console.WriteLine($"AddTransient注入:{object.ReferenceEquals(ts1, ts2)}");
}
//作用域
services.AddScoped<TestServiceImpl>();
using (ServiceProvider AddScoped = services.BuildServiceProvider())
{
var se = new TestServiceImpl(); //注意长生命周期 不要引用比它短周期
using (IServiceScope scope = AddScoped.CreateScope())
{
var t1 = scope.ServiceProvider.GetService<TestServiceImpl>();
var t2 = scope.ServiceProvider.GetService<TestServiceImpl>();
Console.WriteLine($"AddScoped注入:{object.ReferenceEquals(t1, t2)}");
se = t2;
Console.ReadLine();
}
//作用域
using (IServiceScope scope2 = AddScoped.CreateScope())
{
var ts1 = scope2.ServiceProvider.GetService<TestServiceImpl>();
var ts2 = scope2.ServiceProvider.GetService<TestServiceImpl>();
Console.WriteLine($"AddScoped2注入:{object.ReferenceEquals(se, ts2)}");
Console.ReadLine();
}
}
可以看到同一个using下 是相同的,当用第一个内 去检验下一个 则为False
微软官方推荐 生命周期的选择:如果类无状态,建议为Singleton;如果类有状态,具有Scope 控制,建议为Scoped ,如果没有并发修改的问题,使用Transient的时候要谨慎!
参考:ASP.NET Core 依赖注入