Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Dependency Injection IdbConnection

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

like image 650
Christoph Adamakis Avatar asked Jul 05 '18 15:07

Christoph Adamakis


People also ask

What is the difference between IDbConnection and SqlConnection?

Answers. SqlConnection is used to connect to Sql Server databases only. IDbConnection is a generic interface.

What is IDbConnection in C#?

The IDbConnection interface enables an inheriting class to implement a Connection class, which represents a unique session with a data source (for example, a network connection to a server). For more information about Connection classes, see Connecting to a Data Source.

What is dapper in dotnet core?

What is Dapper? Dapper is a simple Object Mapping Framework or a Micro-ORM that helps us to Map the Data from the Result of an SQL Query to a . NET Class efficiently. It would be as simple as executing a SQL Select Statement using the SQL Client object and returning the result as a Mapped Domain C# Class.

When using DI in controller shall I call IDisposable on any injected service?

Instead, you should only place IDisposable on the implementation. This frees any consumer of the abstraction from the doubts whether it should or shouldn't call Dispose (because there is no Dispose method to call on the abstraction).


1 Answers

I Believe I found it. It is

services.AddTransient<IDbConnection>(db => new SqlConnection(
                    Configuration.GetConnectionString("AppConnectionString")));
like image 90
Christoph Adamakis Avatar answered Oct 08 '22 07:10

Christoph Adamakis