Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

injecting connection strings to DI resolved classes

I am using Castle to create my database context based on a given interface. I have the following code in my Installer class and this works fine at the moment.

private ConfigureDelegate ConfigureContext()
{
    return p => p.Named(p.ServiceType.Name)
        .LifeStyle.PerWebRequest
        .DependsOn(new { connectionString = ConfigurationManager.ConnectionStrings["conStringName"].ConnectionString });
}

However i now have a scenario where this installer will find more than one concrete implementation of my interface, where each one should have a different connection string supplied.

Is this possible - if so, could someone point me in the right direction.

TIA

like image 477
Adam Stewart Avatar asked May 05 '11 16:05

Adam Stewart


1 Answers

Yes, it's possible if you can write a piece of code that provides the connection string name for the service. Perhaps something like this:

private ConfigureDelegate ConfigureContext()
{
    return p => p.Named(p.ServiceType.Name)
        .LifeStyle.PerWebRequest
        .DependsOn(new
        {
            connectionString =
                ConfigurationManager
                    .ConnectionStrings[GetConnectionName(p.ServiceType.Name)]
                    .ConnectionString
        });
}

private string GetConnectionName(string serviceName)
{
    // return the connection name
}
like image 137
Mark Seemann Avatar answered Jan 03 '23 16:01

Mark Seemann