10

I have a .NET MVC app that uses autofac for Dependency Injection. When the app starts the following code registers IDbConnection

var connectionString =  ConfigurationManager.ConnectionStrings["DBConnectionStringName"].ConnectionString;
this.Register(c => new SqlConnection(connectionString)).As<IDbConnection>().InstancePerRequest();

I am trying to find how to do the same in .Net Core MVC using the default dependency injection mechenism that the framework offers. I am thinking of adding something like this

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IDbConnection, SqlConnection>();

but I don't know where to add the connection string

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Christoph Adamakis
  • 865
  • 2
  • 9
  • 26

1 Answers1

21

I Believe I found it. It is

services.AddTransient<IDbConnection>(db => new SqlConnection(
                    Configuration.GetConnectionString("AppConnectionString")));
Christoph Adamakis
  • 865
  • 2
  • 9
  • 26
  • Yes using the factory delegate overload is the correct approach in this scenario. – Nkosi Jul 05 '18 at 15:14
  • 6
    `AddScoped` would be the equivalent of `InstancePerRequest`. `AddTransient` is the equivalent of `InstancePerDependency`. – Steven Jul 06 '18 at 06:49
  • Are you sure for that? I thought it was the opposite. I thought AddScoped is the equivalent for InstancePerDependency – Christoph Adamakis Jul 06 '18 at 10:11
  • 1
    I'm getting mixed results with this and I think it might have something to do with how connection pooling is done. Basically, I have 3 repositories that all have IDbConnection injected as transient. If I query each repository in parallel, I get a MARS error which tells me they're all using the same connection. – Sinaesthetic Apr 09 '19 at 20:35
  • If you make IDbConnection transient, will this conflict with singleton Business Services? I'd rather not make my stateless Business Services transient since that will consume unnecessary memory. – Exegesis Jul 30 '21 at 15:54