3

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so there is no way to change connection string in runtime and connect to different databases using the same DbContext ?
No. You must use a separate DbContext for each database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.