Boubakr Chieb
Boubakr Chieb

Reputation: 127

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; }

Upvotes: 3

Views: 1553

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88871

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.

Upvotes: 1

Related Questions