Using same parameter value in a dependency with Windsor

218 views Asked by At

Not even sure this can be done and may need to re-think the whole thing, however thought I would ask before doing that.

Ok I have a repository class with the following constructor

    public Repository(ISessionManager sessionManager, string dbName)
    {
        this.sessionManager = sessionManager;
        this.dbName = dbName;
    }

At present anywhere in the application that needs to use a repository it uses dependency injection and the repository are registered with the container like so.

Component.For<IRepository<User, int>>().ImplementedBy<Repository<User, int>>()
                     .DependsOn(Dependency.OnValue("dbName", "admin")),

What I am looking to do is push the setting of the database name up a level to the services which will use the repositories.

For example having a service with the constructor

public SecurityService(ITransactionFactory transactionFactory,
                       IRepository<User, int> userRepository,
                       string dbName)

I want the argument dbName to be registered with the container against ServiceService and have that value passed when injecting the argument userRepository.

So if another service needs to use the same repository with a different database then when it is registered a new name is provided.

Is this possible?

1

There are 1 answers

1
eouw0o83hf On BEST ANSWER

There's no way that I'm aware of to do exactly what you're looking for, but using named registrations may get you to the same end-goal in a way that's a bit more Windsor-"correct".

For instance, the following two registrations could live in tandem:

Component.For<IRepository<User, int>>()
         .ImplementedBy<Repository<User, int>>()
         .DependsOn(Dependency.OnValue("dbName", "admin")
         .Named("adminRepositoryRegistration")

Component.For<IRepository<User, int>>()
         .ImplementedBy<Repository<User, int>>()
         .DependsOn(Dependency.OnValue("dbName", "user")
         .Named("userRepositoryRegistration")

Then you could wire up your services to depend on the particular registrations in Windsor. For instance, this one would be bound to the first registration:

Component.For<IUserService>()
         .ImplementedBy<UserService>()
         .DependsOn(Dependency.OnComponent("userRepository", "userRepositoryRegistration")

and this will bind to the second:

Component.For<ISecurityService>()
         .ImplementedBy<SecurityService>()
         .DependsOn(Dependency.OnComponent("adminRepository", "adminRepositoryRegistration")

Overall I feel like it gives a bit cleaner of a solution, since it handles all of the dependency provisioning in the DI registration instead of leaving any loose ends to wrap up in the actual services, and allows you to route dependencies as needed.