Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 307
Tim Avatar asked Oct 06 '12 18:10

Tim


1 Answers

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.

like image 115
Nicolay Velizhanin Avatar answered Nov 14 '22 08:11

Nicolay Velizhanin