C
C#11mo 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;
}
}
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();
}
}
}
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?
2 Replies
Angius
Angius11mo ago
Just use DI One, it's easier because you don't need to do the disposing yourself Two, you leave the decision on when to spawn a new context and when to dispose of it to the framework And believe me, the framework knows best when to do those things
Camster
Camster11mo ago
Thanks for your input 🙂
Want results from more Discord servers?
Add your server
More Posts