使用MiniProfiler和EF 5和Autofac剖析DbContext的正确方法

编程入门 行业动态 更新时间:2024-10-26 14:35:24
本文介绍了使用MiniProfiler和EF 5和Autofac剖析DbContext的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

MiniProfiler网站提供了以下用于生成实体框架ObjectContext的代码:

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 }

但是,使用Entity Framework 5,我没有使用ObjectContext-而是使用了DbContext.我不能在此处插入型号名称,因为CreateObjectContext<T>()方法期望T的类型为ObjectContext. (出于同样的原因,此答案中给出的代码也不起作用).

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).

此外,我正在使用autofac初始化我的Db连接.正在使用以下内容(MyData =我的EF DataContext的名称)进行注册:

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();

因此结合了两个部分:如何使用autofac初始化绑定到MiniProfiler.EF的DbContext?如果不可能,那么至少我该如何做第一部分(为MiniProfiler.EF创建工厂方法以返回DbContext)?

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)?

推荐答案

有一个DbContext类的.aspx"rel =" noreferrer>构造函数,它采用现有的DbConnection

There is a constructor of the DbContext class which takes an existing DbConnection

因此,您在MyData上需要一个新的构造器,该构造器仅调用基础

So you need a new contructor on your MyData which just calls the base

public class MyData : DbContext { public MyData(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } //.. }

然后您将MyData注册到Register:

builder.Register(c => { var conn = new EFProfiledDbConnection(GetConnection(), MiniProfiler.Current); return new MyData(conn, true); }).As<DbContext>().InstancePerHttpRequest();

更多推荐

使用MiniProfiler和EF 5和Autofac剖析DbContext的正确方法

本文发布于:2023-11-05 21:18:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法   EF   MiniProfiler   DbContext

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!