![](/img/trans.png)
[英]Register multiple instances of IHostedService with different constructor parameters (DI and non-DI) in .NET Core
[英].NET Core DI, ways of passing parameters to constructor
具有以下服务构造函数
public class Service : IService
{
public Service(IOtherService service1, IAnotherOne service2, string arg)
{
}
}
.NET Core IOC机制传递参数有哪些选择
services.AddSingleton<IOtherService , OtherService>();
services.AddSingleton<IAnotherOne , AnotherOne>();
services.AddSingleton<IService>(x =>
new Service(
services.BuildServiceProvider().GetService<IOtherService>(),
services.BuildServiceProvider().GetService<IAnotherOne >(),
""));
还有其他方法吗?
工厂委托的表达式参数(在本例中为x )是一个IServiceProvider
。
使用它来解决依赖关系:
_serviceCollection.AddSingleton<IService>(x =>
new Service(x.GetRequiredService<IOtherService>(),
x.GetRequiredService<IAnotherOne>(),
""));
工厂委托是延迟调用。 每当要解析类型时,它都会将完成的提供程序作为委托参数传递。
实现此目的的推荐方法是使用选项模式- 请注意,这适用于任何 .NET Core/5 应用程序,而不仅仅是 ASP.NET Core。 但是有些用例是不切实际的(例如,当参数仅在运行时已知,而不是在启动/编译时已知时)或者您需要动态替换依赖项。
当您需要替换单个依赖项(无论是字符串、整数还是其他类型的依赖项)或使用仅接受字符串/整数参数且需要运行时参数的第 3 方库时,它非常有用。
您可以尝试使用CreateInstance<T>(IServiceProvider, Object[])
作为快捷方式,而不是手动解析每个依赖项:
_serviceCollection.AddSingleton<IService>(x =>
ActivatorUtilities.CreateInstance<Service>(x, "");
);
传递给服务构造函数的参数( CreateInstance<T>
/ CreateInstance
的object[]
参数)允许您指定应该直接注入的参数,而不是从服务提供者解析。 它们在出现时从左到右应用(即第一个字符串将被替换为要实例化的类型的第一个字符串类型参数)。
ActivatorUtilities.CreateInstance<Service>
在许多地方用于解析服务并替换此单个激活的默认注册之一。
例如,如果您有一个名为MyService
的类,并且它有IOtherService
、 ILogger<MyService>
作为依赖项,并且您想解析该服务但将IOtherService
的默认服务(假设它是OtherServiceA
)替换为OtherServiceB
,则您可以执行以下操作:
myService = ActivatorUtilities.CreateInstance<Service>(serviceProvider,
new OtherServiceB());
然后IOtherService
的第一个参数将被注入OtherServiceB
,而不是OtherServiceA
- 但其余参数将来自服务提供者。
当您有许多依赖项并且只想特别处理单个依赖项时,这很有用(即,将特定于数据库的提供程序替换为在请求期间或为特定用户配置的值,您仅在运行时和/或请求期间知道的值) - 不是在构建/启动应用程序时)。
如果性能是一个问题,您可以使用ActivatorUtilities.CreateFactory(Type, Type[])
来创建工厂方法。 GitHub 参考和基准测试。
这在非常频繁地解析类型时很有用(例如在 SignalR 和其他高请求场景中)。 基本上,您将通过创建一个ObjectFactory
var myServiceFactory = ActivatorUtilities.CreateFactory(typeof(MyService), new object[] { typeof(IOtherService), });
然后缓存它(作为变量等)并在需要时调用它:
MyService myService = myServiceFactory(serviceProvider, myServiceOrParameterTypeToReplace);
这一切也适用于原始类型 - 这是我测试过的示例:
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddTransient<HelloWorldService>();
services.AddTransient(p => p.ResolveWith<DemoService>("Tseng", "Stackoverflow"));
var provider = services.BuildServiceProvider();
var demoService = provider.GetRequiredService<DemoService>();
Console.WriteLine($"Output: {demoService.HelloWorld()}");
Console.ReadKey();
}
}
public class DemoService
{
private readonly HelloWorldService helloWorldService;
private readonly string firstname;
private readonly string lastname;
public DemoService(HelloWorldService helloWorldService, string firstname, string lastname)
{
this.helloWorldService = helloWorldService ?? throw new ArgumentNullException(nameof(helloWorldService));
this.firstname = firstname ?? throw new ArgumentNullException(nameof(firstname));
this.lastname = lastname ?? throw new ArgumentNullException(nameof(lastname));
}
public string HelloWorld()
{
return this.helloWorldService.Hello(firstname, lastname);
}
}
public class HelloWorldService
{
public string Hello(string name) => $"Hello {name}";
public string Hello(string firstname, string lastname) => $"Hello {firstname} {lastname}";
}
// Just a helper method to shorten code registration code
static class ServiceProviderExtensions
{
public static T ResolveWith<T>(this IServiceProvider provider, params object[] parameters) where T : class =>
ActivatorUtilities.CreateInstance<T>(provider, parameters);
}
印刷
Output: Hello Tseng Stackoverflow
如果您对新服务感到不舒服,可以使用Parameter Object
模式。
所以把字符串参数提取成它自己的类型
public class ServiceArgs
{
public string Arg1 {get; set;}
}
构造函数现在看起来像
public Service(IOtherService service1,
IAnotherOne service2,
ServiceArgs args)
{
}
和设置
_serviceCollection.AddSingleton<ServiceArgs>(_ => new ServiceArgs { Arg1 = ""; });
_serviceCollection.AddSingleton<IOtherService , OtherService>();
_serviceCollection.AddSingleton<IAnotherOne , AnotherOne>();
_serviceCollection.AddSingleton<IService, Service>();
第一个好处是如果您需要更改 Service 构造函数并向其添加新服务,那么您不必更改new Service(...
调用。另一个好处是设置更简洁一些。
对于只有一个或两个参数的构造函数,这可能太多了。
您也可以使用此过程注入依赖项
_serviceCollection.AddSingleton<IOtherService , OtherService>();
_serviceCollection.AddSingleton<IAnotherOne , AnotherOne>();
_serviceCollection.AddSingleton<IService>(x=>new Service( x.GetService<IOtherService>(), x.GetService<IAnotherOne >(), "" ));
即使您有多个参数,也可以使用以下方法
services.AddSingleton(_ => new YourService("yourvalue1","yourvalue2") as IYourService);
但是我觉得它的执行方式不是很有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.