在基于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),它包含与后端数据库通信所需的所有东西。
public class MyClassLib
{
private readonly BloggingContext _context;
public MyClassLib(BloggingContext context)
{
_context = context;
}
}
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类访问这个相同的连接字符串吗?
在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",
}
}
我猜你可以在你的UI MVC项目json文件中声明连接字符串,并在DAL中访问这个相同的连接字符串,在构造函数中使用和注入IConfiguration
(类似于this)。
但请注意它可以not be done for CreateDbContext
。
如果要将其用于向DAL添加迁移,则必须以某种方式指出启动项目和迁移项目,如this answer中所示。