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.
- So in our case can we access this Dependency Injection in BLL like so ?
public class MyClassLib
{
private readonly BloggingContext _context;
public MyClassLib(BloggingContext context)
{
_context = context;
}
}
- Also we need to do scaffolding against an existing database and as such DbContext class will be created in DAL project. OnConfiguring method will be defined in this created DbContext class. Here connection string is hard coded in class.
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 ?