标签:activator 激活 mic ati int oid tps ram enc
当某些服务不方便依赖注入时使用
比如: public Some(serviceA a,ServiceB b,int c)
如上诉方法,c为int时,并不好注入。此时就可以使用ActivatorUtilities 辅助实例化。
ActivatorUtilities 需要一个服务提供者,比如已经注入了serviceA,合serviceB,则在CreateInstance时,只需要补充参数c的值即可。
即:ActivatorUtilities.CreateInstance(serviceProvider,1);
public class Program
{
public static void Main()
{
ServiceCollection serviceDescriptors = new();
var pr = serviceDescriptors.AddScoped<ServiceA>().BuildServiceProvider();
var serviceB = ActivatorUtilities.CreateInstance<ServiceB>(pr, TypeEn.A);
serviceB.ShowType();
serviceB = ActivatorUtilities.CreateInstance<ServiceB>(pr, TypeEn.B);
serviceB.ShowType();
}
public enum TypeEn
{
A,
B
}
public class ServiceA
{
}
public class ServiceB
{
public TypeEn Type { get; set; }
public ServiceA A { get; set; }
public ServiceB(ServiceA a, TypeEn type)
{
this.A = a;
this.Type = type;
}
public void ShowType()
{
System.Console.WriteLine(Type);
}
}
}
标签:activator 激活 mic ati int oid tps ram enc
原文地址:https://www.cnblogs.com/yeqifeng2288/p/14445937.html