Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ConnectionString name in parameter

Tags:

c#

autofac

I currently have an autofac section in my web.config that looks like this.

<autofac>
  <components>
    <component type="MilepointLog.Repositories.Repository, MilepointLog.Repositories" 
               service="MilepointLog.Repositories.IITDMilepointRepository, MilepointLog.Repositories">
      <parameters>
        <parameter name="connectionString" value="test" />
      </parameters>
    </component>
  </components>
</autofac>

What I need to do is using the connection string I have above this code as the value. The connectionStringName is called MilePointLog.

Here is the section in my Global.Asax that has the other autofac code.

var builder = new ContainerBuilder();
builder.RegisterModule(new ConfigurationSettingsReader("autofac"));

builder.RegisterType<Service>()
       .As<IITDMilePointService>().InstancePerRequest();
//builder.RegisterType<Repository>()
//       .As<IITDMilepointRepository>()
//       .WithParameter("connectionString", ConfigurationManager.ConnectionStrings["MilePointLog"].ConnectionString);
builder.RegisterType<HomeController>()
       .InstancePerRequest();

Is what I'm trying to do possible and if so can you tell me how?

like image 477
Tyddlywink Avatar asked Dec 20 '25 21:12

Tyddlywink


1 Answers

Autofac doesn't support what you want out of the box.

The solution I would recommend is to change the implementation of your Repository to accept a named connectionstring.

public class Repository 
{
    public Repository(String connectionStringName)
    {
        String connectionString = 
            ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;

        // ...
    }
}
like image 147
Cyril Durand Avatar answered Dec 23 '25 10:12

Cyril Durand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!