Have DbContext Dependency Injection available in Class library project. Is it possible?

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

Question

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.

  1. 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;
        }
    }
  1. 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 ?

1
1
10/16/2018 11:21:23 AM

Popular Answer

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.

0
3/8/2019 3:47:06 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow