我的DbContext如何处理?(How is my DbContext being disposed?)
我将单片ASP.NET MVC应用程序拆分为N层应用程序时遇到了很大困难。 在下面的示例中,在第一次调用_messageRepo.Create()期间,抛出一个异常,说DbContext因为它已被释放而无法使用。
我无法看到这是怎么回事,并且试图打破Dispose()方法实际上并没有导致应用程序在调试期间中断。
基本结构如下:
- 控制器注入他们使用的每个服务的实例//即:public MyController(IMessageService messageService)
- 服务包含任何所需的存储库实例(即: _messageRepository )
- 存储库使用MyContext的实例,这是DbContext的子类
只要需要,就会重建这些实例,如下例所示
using(var context = new MyContext()) { _messageRepo = new MessageRepository(context); _idRepo = new IdentityRepository(context); var status = _messageRepo.GetStatus(Int32.Parse(message.To)); message.To = status.Header.From.Name; message.ToHash = Obfuscate.SaltAndHash(message.To); message.Subject = "RE:" + status.Header.Subject; var toUser = _idRepo.Get(message.To); var fromUser = _idRepo.Get(_userName); var rawMessage = new Message() { Content = message.Content, Attachments = GetAttachments(message.AttachmentIds) }; var header = new MessageHeader() { To = toUser, From = fromUser, Subject = message.Subject }; _messageRepo.Create(new MessageStatus() { CreatedAt = DateTime.Now, IsRead = false, IsSpam = false, IsTrash = false, Message = rawMessage, Header = header, Owner = header.To }); _messageRepo.Create(new MessageStatus() { CreatedAt = DateTime.Now, IsRead = false, IsSpam = false, IsTrash = false, Message = rawMessage, Header = header, Owner = header.From }); context.Commit(); Email.SendNewMessageNotification(fromUser.Email, toUser.Email); }
存储库方法是LINQ单行程序,它使用代码第一种方法通过Entity Framework从数据库中检索模型。
这种方法有问题吗? 我最初确实有MyContext实现IUnitOfWork,但我删除了它,直到我得到这个不太复杂的方法功能。
另外,我正在使用IoC框架(AutoFac)来加载这些接口实现的实例。 如果这是问题,那么我需要更改我的逻辑以适应AutoFac?
//in Global.asax.cs builder.RegisterType<PonosContext>().As<PonosContext>().InstancePerHttpRequest(); //Example repo constructor public MessageRepository(PonosContext context) { _db = context; }
I am having a great deal of difficulty in splitting my monolithic ASP.NET MVC application into an N-tier app. In the following example, during the first call to _messageRepo.Create() an exception is thrown saying that the DbContext cannot be used since it was already disposed.
I cannot see how that is happening, and attempting to break on the Dispose() method doesn't actually cause the application to break during debugging.
The basic structure is as follows:
- Controllers are injected with instances of each service they use //ie: public MyController(IMessageService messageService)
- Services contain any needed instances of repositories (ie: _messageRepository)
- Repositories utilize an instance of MyContext, a sub-class of DbContext
These instances are reconstructed whenever needed as in the following example
using(var context = new MyContext()) { _messageRepo = new MessageRepository(context); _idRepo = new IdentityRepository(context); var status = _messageRepo.GetStatus(Int32.Parse(message.To)); message.To = status.Header.From.Name; message.ToHash = Obfuscate.SaltAndHash(message.To); message.Subject = "RE:" + status.Header.Subject; var toUser = _idRepo.Get(message.To); var fromUser = _idRepo.Get(_userName); var rawMessage = new Message() { Content = message.Content, Attachments = GetAttachments(message.AttachmentIds) }; var header = new MessageHeader() { To = toUser, From = fromUser, Subject = message.Subject }; _messageRepo.Create(new MessageStatus() { CreatedAt = DateTime.Now, IsRead = false, IsSpam = false, IsTrash = false, Message = rawMessage, Header = header, Owner = header.To }); _messageRepo.Create(new MessageStatus() { CreatedAt = DateTime.Now, IsRead = false, IsSpam = false, IsTrash = false, Message = rawMessage, Header = header, Owner = header.From }); context.Commit(); Email.SendNewMessageNotification(fromUser.Email, toUser.Email); }
The repository methods are LINQ one-liners that retrieve models from a database through Entity Framework using the code first approach.
Is there something wrong with this approach? I did have MyContext implement IUnitOfWork at first, but I removed that until I get this less complicated method functional.
Additionally, I am using an IoC framwork (AutoFac) to load instances of these interface implementations. If this is the problem, then what do I need to change about my logic to accomodate AutoFac?
//in Global.asax.cs builder.RegisterType<PonosContext>().As<PonosContext>().InstancePerHttpRequest(); //Example repo constructor public MessageRepository(PonosContext context) { _db = context; }
原文:https://stackoverflow.com/questions/9484913
最满意答案
如果指定了表单的AcceptButton属性,引用表单上的按钮,则将截取回车键按下。 确保表单没有分配任何AcceptButton,并且文本框应该按下回车键并按预期运行。
更新:如果您想拥有AcceptButton的行为并让RichTextBox在聚焦时按下回车键,则可以通过两种不同的方式实现此目的。 一种是将表单的KeyPreview属性设置为true,并将以下代码添加到表单的KeyPress事件处理程序:
private void Form_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter && this.ActiveControl != theRichTextBox) { this.DialogResult = DialogResult.OK; } }
另一种方法是分配AcceptButton属性,指出一个按钮(然后将其DialogResult属性设置为
OK
)。 然后,您可以为RichTextBox控件的Enter和Leave事件添加事件处理程序,该控件将临时取消分配表单的AcceptButton属性:private void RichTextBox_Enter(object sender, EventArgs e) { this.AcceptButton = null; } private void RichTextBox_Leave(object sender, EventArgs e) { this.AcceptButton = btnAccept; }
If the form's AcceptButton property is assigned, referencing a button on the form, this will intercept the enter key presses. Make sure that the form does not have any AcceptButton assigned, and the text box should receive the enter key presses and behave as expected.
Update: If you want to have the behaviour of the AcceptButton and have the RichTextBox receiving the enter key presses when focused you can achieve this in two different ways. One is to set the KeyPreview property of the form to true, and adding the following code to the KeyPress event handler of the form:
private void Form_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter && this.ActiveControl != theRichTextBox) { this.DialogResult = DialogResult.OK; } }
The other approach is to have the AcceptButton property assigned, pointing out a button (that in turn has its DialogResult property set to
OK
). Then you can add event handlers for the Enter and Leave events for the RichTextBox control that will temporarily un-assign the AcceptButton property of the form:private void RichTextBox_Enter(object sender, EventArgs e) { this.AcceptButton = null; } private void RichTextBox_Leave(object sender, EventArgs e) { this.AcceptButton = btnAccept; }
相关问答
更多-
TCP/IP模型是一个________。[2023-10-02]
a -
下列中不属于面向对象的编程语言的是?[2022-05-30]
a -
不幸的是,智能感知完成的一组触发键不是VB.Net的可配置项。 默认Visual Studio环境中没有办法更改此行为。 可以开发一个插件来实现这一点。 不过这是一个非常极端的措施。 Unfortunately the set of trigger keys for intellisense completion is not a configurable item for VB.Net. There is no way in the default Visual Studio environment to ...
-
VB.NET关闭Excel(VB.NET Closing Excel)[2022-12-15]
您可以向Workbook_BeforeClose添加一些代码,以防止在需要时关闭本书。 您可以通过多种方式执行此操作,最简单的方法是将其直接添加到工作表中,您也可以在vb.net中挂接事件(公共类型事件,我只在VBA中完成它所以无法帮助.net变种) 这是一个可能有效的简单VBA解决方案。 模块 - 给它一个名字,例如:Main Public Sub UnlockWorkbook() Dim Window As Window For Each Window In ThisWorkbook.Windows ... -
如何在vb.net打开文件对话框中选择整个文件夹?(How can I select a whole folder in vb.net open file dialog? [closed])[2022-05-16]
您无法使用OpenFileDialog选择文件夹。 您可以使用FolderBrowserDialog选择一个文件夹。 你是否想要选择文件夹中的所有文件? 如果是这样,请使用FolderBrowserDialog来允许用户选择一个类似于以下内容的文件夹和调用代码: Dim files As String() = Directory.GetDirectories(folderBrowserDialog1.SelectedPath) 您也可以继续使用OpenFileDialog并将其Multiselect属性 ... -
解决方案最终是使用EMGU访问相机; 这也允许同时连接到多个摄像机。 The solution ultimately was to use EMGU to access the camera; this also allows for connecting to multiple cameras at the same time.
-
用sqlite登录vb.net(vb.net login with sqlite)[2022-12-04]
以下是您的代码的两行代码: Dim table As DataTable = Nothing da.Fill(table) 您之间没有任何代码将对象分配给该table变量。 你为什么惊讶这里有一个问题? 如果我告诉你填满一个包,然后递给你没有包,那么你到底要填充它呢? 你不能,因为你不能填充一个不存在的包,但你期望你的应用能够填充一个不存在的DataTable 。 Here are two lines of your code: Dim table As DataTable = Nothing da. ... -
如果指定了表单的AcceptButton属性,引用表单上的按钮,则将截取回车键按下。 确保表单没有分配任何AcceptButton,并且文本框应该按下回车键并按预期运行。 更新:如果您想拥有AcceptButton的行为并让RichTextBox在聚焦时按下回车键,则可以通过两种不同的方式实现此目的。 一种是将表单的KeyPreview属性设置为true,并将以下代码添加到表单的KeyPress事件处理程序: private void Form_KeyPress(object sender, KeyPres ...
-
尝试属性,例如在对话框中设置一些文本框: Property FirstName() As String Get Return txtFirstName.Text End Get Set(ByVal Value As String) txtFirstName.Text = Value End Set End Property Property LastName() As String Get Return txtLastN ...
-
使用FindWindow和SendMessage API 这里用C#,应该是微不足道的转换: using Microsoft.Win32; [DllImport("user32.dll")] public static extern int FindWindow(string lpClassName,string lpWindowName); [DllImport("user32.dll")] public static extern int SendMessage(int hWnd, uint Msg, ...