asp.net-coreentity-framework-coredbcontext

Injecting DbContext in ASP.NET Core - concrete type or interface?


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?


Solution

  • We're always injecting an interface, since it's easier to mock in unit and integration tests.

    1. Are you willing to change the signature of the MessageRepository constructor? It relies on the concrete type.
    2. Do you write tests for your code? Using and interface would make it easier to mock the database context.

    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>());