简体   繁体   中英

Castle Windsor register multiple instances

I am trying to register a different instance of my database depending upon the constructor name. I am familiar with the "first wins" concept in Castle Windsor, but apparently I don't fully understand it.

I would like uaxDB parameter name below to signal ControllerInstaller to give me the instance with UAXmongoURL, UAXmongoConnection parameters. Instead I am getting the first instance, with USERmongoURL and USERmongoconnection parameters. So...first wins, but even when I used named instances? How can I fix so that the named instance trumps any default ordering?

Note I don't just want to swap the order of the two components, because I'm about to have yet more instances so I need to scale beyond 2....said another way, I really need to understand what I'm doing wrong.

// Trying to avoid this constructor declaration in favor of the uncommented constructor
// public DBViewerModel(IMongoConnection devDB, IMongoConnection uaxDB, IMongoConnection prodDB)
public DBViewerModel(IMongoConnection mongoConnection)
{
    //this.devMongoConnection = devDB;
    //this.uaxMongoConnection = uaxDB;
    //this.prodMongoConnection = prodDB;
    this.mongoConnection = mongoConnection;
}

With registration...

container.Register(
    Component
        .For<IMongoConnection>()
        .Named("dataDB")
        .ImplementedBy<MongoConnection>()
        .DependsOn(Property.ForKey("DBlocation").Eq(USERmongoURL),
                   Property.ForKey("DB").Eq(USERmongoCollection))
        .LifeStyle.PerWebRequest,

    Component
        .For<IMongoConnection>()
        .Named("uaxDB")
        .ImplementedBy<MongoConnection>()
        .DependsOn(Property.ForKey("DBlocation").Eq(UAXmongoURL),
                   Property.ForKey("DB").Eq(UAXmongoCollection))
        .LifeStyle.PerWebRequest);

You can specify explicitly what component should be injected by service overrides:

https://github.com/castleproject/Windsor/blob/master/docs/registering-components-one-by-one.md#supplying-the-component-for-a-dependency-to-use-service-override

This is the older way how to do it. If you are using latest version of Windsor, it is prefferable to use DependsOn(Dependency.OnComponent("uaxDB", "uaxDB")) API instead.

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