pomeroy pomeroy - 2 months ago 9
C# Question

Castle Windsor: for N strings, register N instances of a class and pass strings[n] to ctor

I have a service class that connects to a database and pulls data. A new requirement is that I connect to a second (or N) database that has the same schema, and pull the data the same way. (Each DB has different records, being setup regionally).

I'd like to reuse the service class, and just pass in the connection string to the service. (The connection string is currently in App.config).

So, I'd like to register an instance of my service class for each database to which I'd like to connect, passing the connection string to the ctor of the service class.

Is this possible in Castle Windsor?

My best option right now is:

public class ServiceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
foreach (var connection in Properties.Settings.Default.ServicedDBs)
{
container.Register(
Component.For<IService>()
.Named(connection)
.UsingFactoryMethod(() => new Service(
container.Resolve<ILog>(),
connection)));
}
}
}

Answer

It is possible. Implement your service to have a constructor that requests the connection string:

public interface IService { }
public class Service : IService
{
    public Service(string connectionString)
    {
        ConnectionString = connectionString;
    }
    public string ConnectionString { get; set; }
}

And then when registering the component use the .DependsOn to specify the dependencies

public class ServiceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        foreach (var connection in Properties.Settings.Default.ServicedDBs)
        {
           container.Register(
               Component.For<IService>()
                        .ImplementedBy<Service>()
                        .DependsOn(Dependency.OnValue("connectionString", connection)
                        .Named(connection)));
        }
    }
}

You can also have it as a property and use Property Injection to set it but in my opiniton this is a dependency fitting for the constructor. For more about it read: Dependency injection through constructors or property setters?

Comments