【问题标题】:Injecting the database context in an MVC Core project在 MVC Core 项目中注入数据库上下文
【发布时间】:2018-06-07 02:31:43
【问题描述】:

假设我有一个小型 MVC Core 应用程序,我想在两个数据库引擎之间轻松切换(例如,我有 Entity Framework Core 和 MongoDB)。

在我的 appsettings.json 中,我有以下节点:

{
  "UseMongo": false,
  "MongoDB": {
    "ConnectionString": "mongodb://127.0.0.1",
    "DatabaseName": "CoreDB",
    "IsSSL": true
  },
  "EntityDB": {
    "ConnectionString": "mongodb://127.0.0.1",
    "DatabaseName": "CoreDB"
  }
}

然后在我的 Startup.cs 中,我有以下代码:

if (Configuration.GetValue<bool>("UseMongo"))
{
    MongoDbContext.ConnectionString = Configuration.GetSection("MongoDB:ConnectionString").Value;
    MongoDbContext.DatabaseName = Configuration.GetSection("MongoDB:DatabaseName").Value; 
    //Somehow inject context into application so it is available globally               
}
else
{
    EfDbContext.ConnectionString = Configuration.GetSection("EntityDB:ConnectionString").Value;
    EfDbContext.DatabaseName = Configuration.GetSection("EntityDB:DatabaseName").Value;
    //Somehow inject context into application so it is available globally
}

然后我声明一个接口,两个存储库类从该接口派生:

public interface IRepository : IDisposable
{
   void GetData();
}

public class EfRepository : IRepository
{
   public void GetData()
   {
      //DB logic
   }
}

public class MongoRepository : IRepository
{
   public void GetData()
   {
      //DB logic
   }
}

到目前为止一切顺利。现在,我想根据 appsettings.json 中的“UseMongo”开关来使用任一存储库类。我对依赖注入进行了一些研究,但还没有找到解决方案。我希望能够在我的控制器中执行此操作:

public class ValuesController : Controller
{
    private IRepository _repository;

    public ValuesController(IRepository repository)
    {
        _repository= repository;
    }
}

这样的事情可行吗?

【问题讨论】:

    标签: asp.net-mvc dependency-injection asp.net-core repository


    【解决方案1】:

    你可以这样做

    if (Configuration.GetValue<bool>("UseMongo"))
    {
    services.AddScoped(typeof(IRepository),typeof(MongoRepository))
    }
    else
    {
    services.AddScoped(typeof(IRepository),typeof(EfRepository))
    }
    

    【讨论】:

    • 只有一个问题:这是一种好习惯吗?因为我读到的所有注入 DbContext 的示例都使用 services.AddDbContext 来注入上下文。
    • 如何创建 DbContext 实例?您是在存储库中创建它还是使用 DI 注入它?如果你使用 DI,你可以添加 AddDbContext 方法。
    • 我还没有实现那部分,但我计划在我的存储库类中实例化它,所以我想如果我理解正确的话,不使用 AddDbContext 也可以。
    • 如果你在 Repository 中初始化 DB 上下文,你不能对它们进行单元测试。
    猜你喜欢
    • 2021-12-28
    • 2020-11-15
    • 2019-05-27
    • 1970-01-01
    • 2021-01-20
    • 2022-11-13
    • 2019-06-27
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多