【问题标题】:Have DbContext Dependency Injection available in Class library project. Is it possible?在类库项目中提供 DbContext 依赖注入。可能吗?
【发布时间】:2019-03-20 22:03:39
【问题描述】:

在一个基于 Asp.Net Core MVC 的应用程序中,我们知道依赖注入 (DI) 是在 ConfigureServices 方法下的 Startup 类中定义的,如下所示:

var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection)); 

然后我们可以通过构造函数在Controller中使用这个DI:

public class BlogsController : Controller
{
    private readonly BloggingContext _context;

    public BlogsController(BloggingContext context)
    {
        _context = context;
    }

    // GET: Blogs
    public async Task<IActionResult> Index()
    {
        return View(await _context.Blog.ToListAsync());
    }
}

但在实际项目中,为了实现关注点分离,我们利用业务逻辑层(BLL)并为其创建单独的项目。同样,还有一个数据抽象层 (DAL),其中包含与后端数据库通信所需的所有内容。

  1. 那么在我们的例子中,我们可以像这样在 BLL 中访问这个依赖注入吗?

    public class MyClassLib
    {
        private readonly BloggingContext _context;

        public MyClassLib(BloggingContext context)
        {
            _context = context;
        }
    }
  1. 我们还需要对现有数据库进行脚手架,因此 DbContext 类将在 DAL 项目中创建。 OnConfiguring 方法将在这个创建的 DbContext 类中定义。这里的连接字符串在类中是硬编码的。

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
         if (!optionsBuilder.IsConfigured)
         {
             optionsBuilder.UseSqlServer("Server=.;Database=TestDB;user id=sa;password=abcxyz");
         }
    }

但是我们可以在我们的 UI MVC 项目中的某个 json 文件中声明连接字符串,并在 DAL 中使用我们的 DbContext 类访问这个相同的连接字符串吗?

【问题讨论】:

  • 1:是的,DI 在程序集边界上工作正常。一定要注册MyClassLib
  • 2:在启动中进行正常配置,if(!optionsBuilder.IsConfigured) 不会触发。
  • @bommelding 正常配置是什么意思?

标签: c# database entity-framework-core connection-string asp.net-core-2.1


【解决方案1】:

我猜你可以在你的 UI MVC 项目 json 文件中声明连接字符串并在 DAL 中访问这个相同的连接字符串,在构造函数中使用和注入 IConfiguration(类似于 this)。

但请注意它可以not be done for CreateDbContext
如果您想使用它来将迁移添加到您的 DAL,您必须以某种方式指出启动项目和迁移项目,如 this answer 中所示。

【讨论】:

    【解决方案2】:

    在 Startup.cs 类中,您可以找到带有 IConfiguration 参数的 ctor。您可以使用 Get 方法读取 json 并转换为对象。您必须添加 Microsoft.Extensions.Configuration 包才能使用此扩展方法。

    以最简单的方式,当您读取连接时,您可以将其设置为静态类属性。所以我像过去一样创建了 ConfigurationManager 类。

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            ConfigurationManager.ConnectionStrings = Configuration.GetSection("ConnectionStrings").Get<Dictionary<string, string>>();
        }
    

    ConfigurationManager 静态类:

    public static class ConfigurationManager
    {
        public static Dictionary<string, string> ConnectionStrings { get; set; }
    }
    

    现在,我们有了一个带连接的 ConfigurationManager 对象,可以在任何我们想要的地方使用它。让我们在您的 OnConfiguring 方法中调用它:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
         if (!optionsBuilder.IsConfigured)
         {
             optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings ["connectionStringName"]);
         }
    }
    

    如果你想知道 appSettings.json 文件:

    {
      "ConnectionStrings": {
        "yourConnectionName": "Data Source=ConnectionStrings goes here",
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-26
      • 2021-10-23
      • 1970-01-01
      • 2020-03-14
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多