ServiceCollection sc; sc.AddSingleton<Test>(); sc.AddSingleton<ITest>(sp=>sp.GetService<Test>()) //通过类似autofac 可以简化这部分代码.
ServiceProvider.GetService<ITest>() == ServiceProvider.GetService<Test>() //output true.
var test = ServiceProvider.GetService<ITest>() as Test
注册的时候不是应该
sc.AddSingleton<ITest,Test>()
和
sc.AddSingleton<Test>();
sc.AddSingleton<ITest>(sp=>sp.GetService<Test>())
的效果是一样的吗?
@摇曳de风筝: sc.AddSingleton<ITest,Test>() 只能通过GetService<ITest>获取, 用GetService<Test>是拿不到的
sc.AddSingleton<Test>();
sc.AddSingleton<ITest>(sp=>sp.GetService<Test>())
// test
ServiceProvider.GetService<ITest>() == ServiceProvider.GetService<Test>() //output true.