The MiniProfiler site gives the following code for generating an Entity Framework ObjectContext
:
public static MyModel Get()
{
var conn = new StackExchange.Profiling.Data.EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
return ObjectContextUtils.CreateObjectContext<MyModel>(conn); // resides in the MiniProfiler.EF nuget pack
}
However, using Entity Framework 5, I am not using an ObjectContext
- rather I am using a DbContext
. I cannot plug the model name in here, since the CreateObjectContext<T>()
method expects T
to be of type ObjectContext
. (For the same reason, the code given in this answer also doesn't work).
Additionally, I am using autofac to initialize my Db connections. This is being registered with the following (MyData
= the name of my EF DataContext):
Builder.RegisterType<MyData>().As<DbContext>().InstancePerHttpRequest();
So combining two parts: how can I use autofac to initialize my DbContext tied into MiniProfiler.EF? And if that is not possible, at least how can I do the first part (create a factory method for MiniProfiler.EF to return a DbContext
)?
There is a constructor of the
DbContext
class which takes an existingDbConnection
So you need a new contructor on your
MyData
which just calls the baseThen you register your
MyData
withRegister
:I just got this working:
It is based on the code in MiniProfiler's
ObjectContextUtils
.You use it like this:
This solution REQUIRES your
DbContext
to have a constructor which takes aDbConnection
and passes it to base, like this: