.Net Core Dependency Injection IdbConnection

Christoph Adamakis picture Christoph Adamakis · Jul 5, 2018 · Viewed 9.1k times · Source

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

Answer

Christoph Adamakis picture Christoph Adamakis · Jul 5, 2018

I Believe I found it. It is

services.AddTransient<IDbConnection>(db => new SqlConnection(
                    Configuration.GetConnectionString("AppConnectionString")));