In an Asp.Net Core MVC based application, we know that Dependency Injection (DI) is defined right in Startup class under ConfigureServices method like so:
var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
And then we can make use of this DI in Controller via constructor like so:
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());
}
}
But in a real project in order to achieve separation of concerns, we make use of Business Logic Layer (BLL) and create separate project for it. Similarly there is also a Data Abstraction Layer (DAL) which contains all the stuff needed to communicate with the backend Database.
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");
}
}
But can we declare Connection string in our UI MVC project in some json file and access this same connection string in DAL with in our DbContext class ?
I guess you can declare connection strings in your UI MVC project json file and access this same connection string in DAL, using and inject IConfiguration
in the constructor (similar like this).
But note it can not be done for CreateDbContext
.
If you want to use it for adding migrations to your DAL, you have to somehow point out the startup project and the migrations project, like illustrated in this answer.