简体   繁体   中英

ASP.NET MVC. Autofac and multiple connection strings

I need to use multiple connections string in my ASP.NET MVC application. How I can to do it? Now i'm registering connection as following:

builder.RegisterType<SqlConnection>().WithParameter(
    "connectionString",
    WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)
  .InstancePerLifetimeScope()
  .ExternallyOwned();

builder.Register(c => new ContextDataContext(c.Resolve<SqlConnection>())).InstancePerDependency();

You can register multiple instances of a given type by name:

From Autofac tutorial:

builder.Register<OnlineState>().Named<IDeviceState>("online");

To retrieve a named service, the ResolveNamed() method is used:

var r = container.ResolveNamed<IDeviceState>("online");

http://autofac.readthedocs.org/en/latest/advanced/keyed-services.html

One way to do it, is to create your own connection factory, and register it with autofac. Something like:

interface IConnectionFactory{
   SqlConnection CreateConnection(string connectionStringName);
}

You can define multiple connection strings in section in web.config

<connectionStrings>

    <add name="ProductConnection" providerName="System.Data.SqlClient" connectionString="_YOUR_CONNECTION_STRING_1_"/>

    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="_YOUR_CONNECTION_STRING_2_"/>

</connectionStrings>

In your code you can use like,

ConfigurationManager.ConnectionStrings["ProductConnection"] to get the connection string.

In case you want to get an instance based on connection string, you can use any factory which can resolve your instance based on connection string name. SimpleFactory + Unity or SimpleFactory + Autofac can help you in this.

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