标签:builds ges 配置 build manager transient read string Plan
依赖注入入门 全面理解 ASP.NET Core 依赖注入
// redis注入
services.AddSingleton<IRedisConnection>(k => { return new RedisConnection(6, Configuration["RedisConnectionString"]); });
方式一.
services.AddSingleton<IConnectionMultiplexer, ConnectionMultiplexer>(x =>
{ return x.GetService<IRedisConnection>().ConnectionMultiplexer; });
方式二
var sp = services.BuildServiceProvider();
services.AddSingleton<StackExchange.Redis.IConnectionMultiplexer>((x) => { return sp.GetService<IRedisConnection>().ConnectionMultiplexer; });
services.AddScoped<ICacheManager, RedisCacheManager>();
比如有一个接口
IFlyProvider{ Fly(); };
俩个实现类
FlyByPlaneProvider{};
FlyByRocketProvider{};
如何配置?
1. 先用断子绝孙法直接注册两个实现类
services.AddTransient<FlyByPlaneProvider>();
services.AddTransient<FlyByRocketProvider>();
2. 注册一个返回 Func<string,IFlyProvider>的项
services.AddTransient<Func<string, IFlyProvider>>(serviceProvider => key =>
{if (key == "plane")
return serviceProvider.GetService<CreateWezhanResponseProvider>();
else
return serviceProvider.GetService<FlyByRocketProvider>();//用到了上面提到的 直接调用刚刚添加好的注册
});
3. 使用
比如, 这里有一个旅游管理 ITravelManager接口, 里面有个方法, FLyToRoma(string key)
那么我们需要在实现类中
public class TravelManager: ITravelManager
{private readonly Func<string, IFlyProvider> _providerAccessor;
FLyToRoma(string key){
var provider=_providerAccessor(key);
provider.Fly();
…………………
}
标签:builds ges 配置 build manager transient read string Plan
原文地址:https://www.cnblogs.com/jianjialin/p/9543851.html