2

When using Redis, we create a ConnectionMultiplexer and from that GetDatabase() to get access to a given cache.

I want to configure Unity to do this as follows:

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
container.RegisterInstance(redis);
container.RegisterType<IDatabase, redis.GetDatabase()>();

But not surprisingly that wont compile.

The only other way I can think of at the moment is to create a database factory class and pass that into my controllers instead of an IDatabase but that seems like overkill as I would just essentially be wrapping a wrapper:

 public static void RegisterComponents() {
    ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
    container.RegisterInstance(redis);
    RedisDatabaseFactory redisDbf = new RedisDatabaseFactory(redis);
    container.RegisterInstance(redisDbf);
    container.RegisterType<IRedisDatabaseFactory, RedisDatabaseFactory>();
}

MyController.cs

public MyController(IRedisDatabaseFactory rdbf){
  _db = rdbf.GetDatabase();
}

So short of using this overly verbose factory method, how can I use the methods of registered instances to create injectable dependencies for other objects?

1 Answer 1

4

You can register a factory method for IDatabase using InjectionFactory:

container.RegisterType<IDatabase>(new InjectionFactory(c => redis.GetDatabase()));
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect, I knew there had to be a shorthand.
No worries. If you wanted to get the database from the registered ConnectionMultiplexer then you can resolve it from the container parameter (c in the above code)
Do you mean like this: container.RegisterType<IDatabase>(new InjectionFactory(c => c.Resolve<ConnectionMultiplexer>().GetDatabase())); is that not the same thing? Or is there a different scope between that and your answer?
Yes, that's what I mean. In reality, both ConnectionMultiplexer and IDatabase are thread safe and can be passed around so can be registered with singleton lifestyle, meaning the above has the same outcome as my answer. But it's worth knowing that in case you have services that do not have singleton lifestyle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.