在StackExchange.Redis docs中,建议仅创建一个并重新使用与Redis的连接。
Azure Redis best practices建议使用以下模式:
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect("cachename.redis.cache.windows.net,ssl=true,abortConnect=false,password=password");
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
但是我应该如何使用Autofac,我希望在web / app配置文件中设置配置?
我目前有一个RedisCacheProvider:
private readonly ConnectionMultiplexer _connection;
public RedisCacheProvider(string config)
{
_connection = ConnectionMultiplexer.Connect(config);
}
并在我的Autofac配置中:
builder.RegisterType<RedisCacheProvider>().As<ICacheProvider>().WithParameter("config", "localhost");
我的想法是,我应该更改我的RedisCacheProvider以接收通过静态变量传入的ConnectionMultiplexer?
更新:到目前为止我的解决方案:
我的RedisCacheProvider(在这里注入一个接口允许我在单元测试中模拟连接):
private readonly IConnectionMultiplexer _connection;
public RedisCacheProvider(IConnectionMultiplexer connection)
{
_connection = connection;
}
RedisConnection类用于保存静态属性并从配置文件中读取配置:
public class RedisConnection
{
private static readonly Lazy<ConnectionMultiplexer> LazyConnection =
new Lazy<ConnectionMultiplexer>(
() => ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisCache"]));
public static ConnectionMultiplexer Connection
{
get
{
return LazyConnection.Value;
}
}
}
在Autofac模块中注册:
builder.RegisterType<RedisCacheProvider>().As<ICacheProvider>()
.WithParameter(new TypedParameter(
typeof(IConnectionMultiplexer),
RedisConnection.Connection));
答案 0 :(得分:3)
Autofac支持隐式关系类型和Lazy&lt;&gt;开箱即用支持评估。 因此,在您的示例中注册RedisCacheProvider之后,就是
builder
.RegisterType<RedisCacheProvider>()
.As<ICacheProvider>()
.WithParameter("config", "localhost");
你可以像下面这样解决它:
container.Resolve<Lazy<ICacheProvider>>()
但不要忘记默认的Autofac生命周期范围是InstancePerDependency(transient)。也就是说,每次解决它或者将其作为依赖项提供给其他组件时,您将获得RedisCacheProvider的新实例。要解决此问题,您需要明确指定其生命周期范围。例如,要使其成为单身人士,您需要更改注册,如下所示:
builder
.RegisterType<RedisCacheProvider>()
.As<ICacheProvider>()
.WithParameter("config", "localhost")
.SingleInstance();
此处的另一个假设是RedisCacheProvider是唯一使用Redis连接的组件。如果不是这样的话,那么你最好让Autofac管理Redis连接的生命范围(无论如何都是更好的想法)并在RedisCacheProvider中将连接作为依赖关系。那就是:
public RedisCacheProvider(IConnectionMultiplexer connection)
{
this.connection = connection;
}
....
builder
.Register(cx => ConnectionMultiplexer.Connect("localhost"))
.As<IConnectionMultiplexer>()
.SingleInstace();
builder
.RegisterType<RedisCacheProvider>()
.As<ICacheProvider>();