开发者

injecting connection strings to DI resolved classes

开发者 https://www.devze.com 2023-03-04 09:41 出处:网络
I am using Castle to creat开发者_StackOverflow中文版e my database context based on a given interface. I have the following code in my Installer class and this works fine at the moment.

I am using Castle to creat开发者_StackOverflow中文版e 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


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消