Using what's the preferred way to combine Autofac and Dapper

autofac c# dapper inversion-of-control ioc-container

Question

We've been using EF as the backbone for most of the data access in our current app and we're slowly moving away from it for some of the more server-intensive queries and replacing it with Dapper instead.

With this in mind, what's the preferred way to implement the connection with Autofac? Is it to inject an IDBConnection or a connection string? IDBConnection feels better to me but if you use "using" it's disposed and can't be accessed by subsequent calls.

Popular Answer

We have project using both EF and Dapper. We are registering IDbConnection like this:

        builder.Register(c =>
            {
                var db = c.Resolve<MyDbContext>();
                if (db.Database.Connection.State != ConnectionState.Open)
                {
                    db.Database.Connection.Open();
                }
                return db.Database.Connection;
            })
               .As<IDbConnection>()
               .ExternallyOwned() // DbContext owns connection and closes him when disposing.
               .InstancePerHttpRequest();

And injecting IDbConnection in our controllers.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why