.NET Core DI,将参数传递给构造函数的方法
问题描述:
具有以下服务构造函数
public class Service : IService
{
public Service(IOtherService service1, IAnotherOne service2, string arg)
{
}
}
使用.NET Core IOC机制传递参数的选择有哪些
What are the choices of passing the parameters using .NET Core IOC mechanism
_serviceCollection.AddSingleton<IOtherService , OtherService>();
_serviceCollection.AddSingleton<IAnotherOne , AnotherOne>();
_serviceCollection.AddSingleton<IService>(x=>new Service( _serviceCollection.BuildServiceProvider().GetService<IOtherService>(), _serviceCollection.BuildServiceProvider().GetService<IAnotherOne >(), "" ));
还有其他方法吗?
答
工厂委托的表达式参数(在这种情况下为 x )是 IServiceProvider
。
The expression parameter (x in this case), of the factory delegate is a IServiceProvider
.
使用它来解决依赖关系,
Use that to resolve the dependencies,
_serviceCollection.AddSingleton<IService>(x =>
new Service(x.GetRequiredService<IOtherService>(),
x.GetRequiredService<IAnotherOne>(),
""));
工厂委托是延迟调用。每当要解析类型时,它将通过完整的提供程序作为委托参数。
The factory delegate is a delayed invocation. When ever the type is to be resolved it will pass the completed provider as the delegate parameter.