首页 \ 问答 \ 我的DbContext如何处理?(How is my DbContext being disposed?)

我的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
更新时间:2022-12-03 16:12

最满意答案

如果指定了表单的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;
}

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)