.NET Core DI,将参数传递给构造函数的方法 [英] .NET Core DI, ways of passing parameters to constructor
本文介绍了.NET Core DI,将参数传递给构造函数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有以下服务构造函数
公共类服务:IService{公共服务(IOtherService service1,IAnotherOne service2,字符串arg){}}
使用.NET Core IOC机制传递参数有哪些选择
services.AddSingleton();services.AddSingleton();services.AddSingleton(x =>新服务(services.BuildServiceProvider().GetService(),services.BuildServiceProvider().GetService(),"));
还有什么办法吗?
解决方案
工厂委托的表达式参数(在本例中为x)是一个IServiceProvider
.>
使用它来解决依赖关系:
_serviceCollection.AddSingleton(x =>新服务(x.GetRequiredService(),x.GetRequiredService(),"));
工厂委托是延迟调用.每当要解析类型时,它都会将完成的提供程序作为委托参数传递.
Having the following service constructor
public class Service : IService
{
public Service(IOtherService service1, IAnotherOne service2, string arg)
{
}
}
What are the choices of passing the parameters using .NET Core IOC mechanism
services.AddSingleton<IOtherService , OtherService>();
services.AddSingleton<IAnotherOne , AnotherOne>();
services.AddSingleton<IService>(x =>
new Service(
services.BuildServiceProvider().GetService<IOtherService>(),
services.BuildServiceProvider().GetService<IAnotherOne >(),
""));
Is there any other way ?
解决方案
The expression parameter (x in this case) of the factory delegate is an 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. Whenever the type is to be resolved, it will pass the completed provider as the delegate parameter.
这篇关于.NET Core DI,将参数传递给构造函数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文