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
Answers. SqlConnection is used to connect to Sql Server databases only. IDbConnection is a generic interface.
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? 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.
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).
I Believe I found it. It is
services.AddTransient<IDbConnection>(db => new SqlConnection(
Configuration.GetConnectionString("AppConnectionString")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With