On an ASP.NET Core project I am injecting Entity Framework DbContext
:
public MessageRepository(MyDbContext context)
{
}
And the configuration is:
services
.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyDbContext>(x => x.UseSqlServer(connectionString);
Should I create an interface IMyDbContext
public class MyDbContext : DbContext, IMyDbContext
{
}
and inject it instead?
public MessageRepository(IMyDbContext context)
{
}
In all ASP.NET Core examples I see the concrete type, DbContext
, is being injected and not an interface.
What option should I choose?
We're always injecting an interface, since it's easier to mock in unit and integration tests.
MessageRepository
constructor? It relies on the concrete type.If you've answered "no" to one or more of the above, inject the concrete type; otherwise, inject the interface.
[EDIT] use the following.
context services.AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>());