实现此目的的推荐方法是使用Options pattern - 请注意,这适用于任何 .NET Core/5 应用程序,而不仅仅是 ASP.NET Core。但是在某些用例中它是不切实际的(例如,当参数仅在运行时知道,而不是在启动/编译时知道时)或者您需要动态替换依赖项。
当您需要替换单个依赖项(无论是字符串、整数或其他类型的依赖项)或使用仅接受字符串/整数参数且需要运行时参数的 3rd 方库时,它非常有用。
您可以尝试CreateInstance<T>(IServiceProvider, Object[]) 作为快捷方式,而不是手动解决每个依赖项:
_serviceCollection.AddSingleton<IService>(x =>
ActivatorUtilities.CreateInstance<Service>(x, "");
);
传递给服务构造函数的参数(object[] 参数传递给CreateInstance<T>/CreateInstance)允许您指定应直接注入的参数,而不是从服务提供者解析。它们在出现时从左到右应用(即第一个字符串将替换为要实例化的类型的第一个字符串类型参数)。
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 reference 和 benchmark。
当类型被非常频繁地解析时(例如在 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