Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC. Autofac and multiple connection strings

Tags:

c#

autofac

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();
like image 205
alexmac Avatar asked Nov 03 '22 18:11

alexmac


1 Answers

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

like image 55
kubal5003 Avatar answered Nov 11 '22 14:11

kubal5003