C#C
C#3y ago
Camster

✅ EF Core, Proper DbContext Instantiation

When instantiating the DbContext, I've always created it in a Repository class (not a generic repository, rather a unit of work repository). First I extend the DbContext to allow construction via connection string, like so.

    public partial class MyContext {
        public MyContext (string connectionString) : base(GetOptions(connectionString)) { }

        private static DbContextOptions GetOptions(string connectionString) {
            return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
        }
    }


Then in the Repository class, I instantiate it like so:
public class Repository {
    private string _connectionString;
    
    public Repository(string connectionString) {
        _connectionString = connectionString;
    }
    
    public async Task<List<Entity_DTO>> Update_Entity(List<UpdateEntity_DTO> update) {
        using (var context = new MyContext(_connectionString)) {
            // Perform Update
                        await context.SaveChangesAsync();
            return await GetEntityList();
        }
    }
}


This works fine for me, but I've seen a lot of examples where the DbContext is injected in the front-end. Hence, it is never instantiated. My question is, what are the reasons for this? Is it really advantageous to inject the DbContext? Is the way I do it an absolute no-no?
Was this page helpful?