简体   繁体   中英

Register multiple implementations of same interface in Castle Windsor

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM