版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
public void ConfigureServices(IServiceCollection services)
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IProcessingServer, CapProcessingServer>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<IProcessingServer, ConsumerRegister>());
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
这里使用了TryAddEnumerable方法,源码如下:
if (!services.Any(d =>
d.ServiceType == descriptor.ServiceType &&
d.GetImplementationType() == implementationType))
{
services.Add(descriptor);
}
而常用的是TryAddTransient,源码如下:
if (!collection.Any(d => d.ServiceType == descriptor.ServiceType))
{
collection.Add(descriptor);
}
Lifetime:服务的生命周期(Singleton:单例,Scoped:单个请求期间,Transient:暂时的,每次都创建一个实例)
ServiceType:服务类型
ImplementationType:服务的实现类型
ImplementationInstance:实现类型的实例
TryAddEnumerable和TryAddTransient都是用于添加服务,他们的却别就在于过滤条件不同
TryAddEnumerable在添加时会根据服务的ServiceType和ImplementationType进行判断,如果已存在对应的服务则不添加,适用于为同一个服务添加多个不同的实现的场景
TryAddTransient在添加时只根据服务的ServiceType进行判断,如果已存在该类型的服务,则不添加,该方法适用于同一个服务已存在的服务不在添加的场景
TryAddEnumerable 可以同一个接口注册 多个不同的具体实现类,TryAddTransient 如果某个接口已经注册了某一个实现类,就不再添加这个接口的其他实现类了
注入后则可以直接foreach 循环
IEnumerable<IProcessingServer> processors;//
//所有的集合、数组都实现了这个接口因此可以支持foreach。IEnumerable<T>还是从IEnumerable继承而来的,因为.NET 2.0以前没提供IList<T>这样的泛型列表
public ValuesController(IEnumerable<IProcessingServer> processors)
{
this.processors = processors;
}
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
foreach(var item in processors)
{
item.test();//test 方法就是两个服务的实现方法
}
return new string[] { "value1", "value2" };
}