Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work with one dbContext and multiple connection string in EntityFramework and .net core dependency injection

I'm working in a project using EntityFramework Core and .net core 2.0, which I need to connect to multiple databases to get data to execute a cron, I injected DbContext.cs in startup.cs like above:

  services.AddDbContext<DbContext.cs>();

I use it in my UnitOfWork.cs like this:

public class UnitOfWork<Context> : IUnitOfWork where Context : DbContext
    {
        public DbContext _context { get; set; }

        public DbContext getContext()
        {
            return _context;
        }
        public UnitOfWork(DbContext context)
        {
            _context = context;
        }
}

which is also managed by dependency injection.

My question is, is it possible to work with a one injected instance of dbcontext, and change the connection at runtime in need? I really didn't find a clear solution for that. I tried to use a setter and to instantiate a new dbContext every time I need to connect to a new database, but it doesn't seem so beautiful:

public void SetContext(DbContext context)
        {
            _context = context;
        }
public DbContext _context { get; set; }
like image 884
Boubakr Chieb Avatar asked Nov 22 '25 00:11

Boubakr Chieb


1 Answers

is it possible to work with a one injected instance of dbcontext, and change the connection at runtime in need,

No. If your Unit Of Work needs to connect to multiple databases, you need multiple DbContext instances.

like image 109
David Browne - Microsoft Avatar answered Nov 24 '25 16:11

David Browne - Microsoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!