如何在ConfigureServices方法ASP.NET Core中添加db上下文

Buc*_*ead 2 entity-framework-core asp.net-core

是否有可能"在飞行中"在外部类/方法中添加数据库上下文?当我运行应用程序时,没有任何连接字符串,所以我需要在输入一些信息后生成一个数据库(server,dbname,ect)

Ism*_*sma 7

一种方法是使用工厂模式,即创建将用于创建上下文的新实例的服务.

这是一个例子,它不是最终解决方案,您需要根据自己的需要进行调整,但它应该让您了解该技术:

public interface IDbContextFactory
{
    DbContext CreateDbContext(string connectionString);
}

public class DbContextFactory : IDbContextFactory
{
    public DbContext CreateDbContext(string connectionString)
    {
        return new DbContext(connectionString);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在asp.net核心中,您可以注册上下文工厂并将其注入您的控制器:

 services.AddSingleton<IDbContextFactory, DbContextFactory>();

 public class SomeController
 {
      private IDbContextFactory contextFactory;

      public SomeController(IDbContextFactory contextFactory)
      {
          this.contextFactory = contextFactory;
      }

      public IActionResult Index()
      {     
         using(var db = contextFactory.CreateDbContext("Your connection string"))    {
              //Get some data
         }
         return View();
     }
 }
Run Code Online (Sandbox Code Playgroud)

您可以将工厂模式与工作单元和/或存储库模式结合起来,以更好地分离关注点,并确保始终处理上下文等,而不是创建DbContext.