在类库项目中使用DbContext依赖注入。可能吗?

问题描述 投票:0回答:2

在基于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一样在BLL中访问这个依赖注入吗?

    public class MyClassLib
    {
        private readonly BloggingContext _context;

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

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

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

c# database entity-framework-core connection-string asp.net-core-2.1
2个回答
0
投票

在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",
  }
}

0
投票

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

但请注意它可以not be done for CreateDbContext。 如果要将其用于向DAL添加迁移,则必须以某种方式指出启动项目和迁移项目,如this answer中所示。

© www.soinside.com 2019 - 2024. All rights reserved.