如何在IOC中注册多个(不同的)redis连接池

时间:2017-03-23 15:48:21

标签: servicestack

我必须从一个服务连接到不同的Redis实例(每个数据库有一个redis实例,因为它们需要不同的存储策略)。

对于每个Redis DB,我有几个(不同的)存储库,它们在构造函数中采用相应的PooledRedisClientManager实例。我不明白如何正确注册它们,因为它们都实现相同的接口IRedisClientsManager)。

container.Register<IRedisClientsManager>(c => new PooledRedisClientManager(databaseAConnectionString));
container.Register<IRedisClientsManager>(c => new PooledRedisClientManager(databaseBConnectionString));

以上注册仅因连接字符串而异,我不知道如何区分(解决)它们。我应该注册这样的东西:

//Pools for database A and B
var databaseAPool = new PooledRedisClientManager(databaseAConnectionString)
var databaseBPool = new PooledRedisClientManager(databaseBConnectionString)
//Repositories for database A
container.Register(c => new AClass1Repository(databaseAPool);
container.Register(c => new AClass2Repository(databaseAPool);
// etc
//Repositories for database B
container.Register(c => new BClass1Repository(databaseBPool);
container.Register(c => new BClass2Repository(databaseBPool);
// etc

在我的服务中,我喜欢做类似的事情:

//...
var AClass1Repo = ServiceStackHost.Instance.Resolve<AClass1Repository>();
var BClass2Repo = ServiceStackHost.Instance.Resolve<BClass2Repository>();

var xyz = AClass1Repo.GetSomeData(....);
BClass2Repo.StoreSomeData(somePocoInstance);
//....

如何为每个数据库连接不同的Redis连接池和我的存储库?

1 个答案:

答案 0 :(得分:2)

您只能注册1 IRedisClientsManager,因此您无法在IOC中注册2个PooledRedisClientManager实例。您可以在不同的Redis Manager中注册不同的类,但我也会在AppHost上定义他们的单例实例,以便在需要时单独访问它们,例如:

public class AppHost
{
    PooledRedisClientManager RedisManagerA { get; set; }
    PooledRedisClientManager RedisManagerB { get; set; }

    public void Configure(Container container)
    {
        RedisManagerA = new PooledRedisClientManager(databaseAConnString);
        RedisManagerB = new PooledRedisClientManager(databaseBConnString);

        container.Register(c => new AClass1Repository(RedisManagerA);
        container.Register(c => new AClass2Repository(RedisManagerA);

        container.Register(c => new BClass1Repository(RedisManagerB);
        container.Register(c => new BClass2Repository(RedisManagerB);
    }
}

此外,您不需要从服务中访问ServiceStackHost,您可以将它们声明为依赖项并注入它们,例如:

public class MyService : Service
{
    public AClass1Repository ARepo1 { get; set; }
    public BClass1Repository BRepo1 { get; set; }
}