gpt4 book ai didi

autofac - 使用 Autofac 配置 StackExchange.Redis 的最佳实践是什么?

转载 作者:行者123 更新时间:2023-12-04 19:03:16 25 4
gpt4 key购买 nike

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;
}
}

但是我应该如何在我希望在 web/app 配置文件中设置配置的 Autofac 中使用它?

我目前有一个 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 (在这里注入(inject)接口(interface)允许我在单元测试中模拟连接):
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));

最佳答案

Autofac 支持隐式关系类型,并且开箱即用地支持 Lazy<> 评估。
因此,在您按照示例注册 RedisCacheProvider 之后,即

builder
.RegisterType<RedisCacheProvider>()
.As<ICacheProvider>()
.WithParameter("config", "localhost");
你可以像下面这样解决它:
container.Resolve<Lazy<ICacheProvider>>();
但不要忘记默认 Autofac 生命周期范围是 InstancePerDependency(transient)。也就是说,每次解析 RedisCacheProvider 或将其作为依赖项提供给其他组件时,您都会获得新的 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>()
.SingleInstance();

builder
.RegisterType<RedisCacheProvider>()
.As<ICacheProvider>();

关于autofac - 使用 Autofac 配置 StackExchange.Redis 的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com