Let's say I have component that currently has a single dependency on my interface ICache
and is registered with a DB-based Cache implementation using constructor injection. Something like this:
container.Register(Component.For<ICache>()
.ImplementedBy<DatabaseCache>()
.LifeStyle.Singleton
.Named("dbcache"));
and then my component registers it:
container.Register(Component.For<IRepository>()
.ImplementedBy<CoolRepository>()
.LifeStyle.Singleton
.Named("repo")
.DependsOn(Dependency.OnComponent(typeof(ICache), "dbcache")));
But what if I would like my component to be able to make use of a second ICache
dependency of a different type at the same time? How would I inject 2 different implementations of the same interface into the main component?
Use the overload of Dependency.OnComponent
that accepts a string as the first parameter. This is the name of the parameter in the constructor for which the dependency will be supplied. For example, if your CoolRepository
constructor looks like this:
public CoolRepository(ICache first, ICache second)
{
// ...
}
Then your registration will look like this:
// register another cache
container.Register(Component.For<ICache>()
.ImplementedBy<DummyCache>()
.LifeStyle.Singleton
.Named("otherCache"));
container.Register(Component.For<IRepository>()
.ImplementedBy<CoolRepository>()
.LifeStyle.Singleton
.Named("repo")
.DependsOn(Dependency.OnComponent("first", "dbcache"))
.DependsOn(Dependency.OnComponent("second", "otherCache")));
See more details here.