标签:标识 csr class val err style 方案 add single
这里不在介绍依赖注入的基本概念,这里网上/官网上面有很多。
一个接口多个实现依赖注入的问题?
方案1:
这里通过区分标识就可以了.
如:
public interface IRedisMessage { T Get<T>(string key); } public class CSRedis:IRedisMessage { public T Get<T>(string key) { return RedisHelper.Get<T>(key); } } public class StackExchangeRedis:IRedisMessage { public T Get<T>(string key) { return db.StringGet(key); } }
在服务注册的时候 ConfigureServices中
//这里我们需要这样写,常规写法就是正常的服务注册,这里不在写。直接写方案 services.AddSingleton<IRedisManager,CSRedis>();
services.AddSingleton<IRedisManager,StackExchangeRedis>();
services.AddSingleton(factory => { Func< string, IRedisManager> accesor = key => { if(key.Equals( "CSRedis")) { return factory.GetService<CSRedis>();
} else if(key.Equals("StackExchangeRedis")) { return factory.GetService<StackExchangeRedis>();
} else{ thrownewArgumentException($ "Not Support key : {key}");
} };
return accesor;
});
具体实现
private IRedisMananger _iRedisA; private IRedisMananger _iRedisB; privatereadonlyFunc< string, IRedisMananger > _serviceAccessor; publicValuesController(Func<string, IDemoService> serviceAccessor){ this._serviceAccessor = serviceAccessor; _iRedisA= _serviceAccessor( "CSRedis"); _iRedisB= _serviceAccessor( "StackExchangerRedis"); }
方案2:
private IRedisMananger _iRedisA; private IRedisMananger _iRedisB; publicValuesController(IEnumber<IRedisMananger > redisMessages){ _iRedisA= redisMessages.FirstOrDefault(h=>h.GetType(),Name--"CSRedis"); _iRedisB= redisMessages.FirstOrDefault(h=>h.GetType(),Name--"StackExchangerRedis"); }
标签:标识 csr class val err style 方案 add single
原文地址:https://www.cnblogs.com/ccaa/p/12936001.html