如何在单例实例中更新数据库?

时间:2016-12-25 03:40:26

标签: c# asp.net-core singleton entity-framework-core

我的应用程序对处理程序类实例使用单例模式。它负责处理一些事件:

public class MyHandler
{
    public void HandlerEvent(object sender, EventArgs e)
    {
        //want to update DB here
    }
}

可能MyHandler需要开始与DB交互。我可以这样做吗?有我的愿景:

  1. 只需在DbContext处作为单身人员加上MyHandler。显然这是一个坏主意。
  2. 使用ASP.Net Core DI功能并将DbContext发送到MyHandler,但作为实例“每个请求一个”。我认为在我的情况下(MyHandler是单身)这类似于1
  3. 通过using运算符执行,即作为原子事务,例如using(var context = new XDbContext()) {...}至于我,这是一个很好的方法,但实体框架核心实现的DbContext需要DbContextOptions作为其构造函数的参数。如果我为XDbContext声明无参数构造函数,那么它会引发异常。
  4. 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我已经看过ef核心教程(http://codepen.io/anon/pen/ezJGPB),据我所知,DbContextOptions - 只是一个包含配置参数的对象。如果我有同样的问题,我会使用第三种方式(使用),但会创建一个帮助器来注入参数或使用工厂。我在教程中找到了一个工厂的例子

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace MyProject
{
   public class BloggingContextFactory : IDbContextFactory<BloggingContext>
   {
       public BloggingContext Create()
       {
          var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
          optionsBuilder.UseSqlite("Filename=./blog.db");

          return new BloggingContext(optionsBuilder.Options);
       }
   }
}

使用示例:

public class MyHandler
{
   public void HandlerEvent(object sender, EventArgs e)
   {
       // Or make 'Create' method static
       using(var context = new BloggingContextFactory().Create())
       {
                 . . . 
       }
   }
}
相关问题