Inject DbContext in Asp.Net Core. Concrete type or interface?

asp.net-core entity-framework-core

Question

On an Asp.Net Core project I am injecting Entity Framework DbContext:

public MessageRepository(MyDbContext context) {
}

And the configuration is:

services
  .AddEntityFramework()
  .AddSqlServer()
  .AddDbContext<Context>(x => x.UseSqlServer(connectionString);

Should I create an interface, IMyDbContext, and injecting it instead?

public class MyDbContext : DbContext, IMyDbContext { }

public MessageRepository(IMyDbContext context) {
}

In all ASP.NET Core examples I see the concrete type, MyDbContext, is being injected and not an interface ...

What option should I choose?

1
8
4/12/2016 8:28:04 PM

Accepted Answer

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.

1
4/12/2016 9:04:18 PM

Popular Answer

Currently working on a project myself, where I decided to go with 2 interfaces like this

public interface IDbContext : IDisposable
{
    DbContext Instance { get; }
}

and

public interface IApplicationDbContext : IDbContext
{
    DbSet<MyEntity> MyEntities { get; set; }
    ...
}

My concrete DbContext would then just implement the application context interface

public class ApplicationDbContext : DbContext, IApplicationDbContext
{
    public DbContext Instance => this

    public DbSet<MyEntity> MyEntities { get; set; }
}

This allows my implementation of the Application context to be injected as the application context interface, while also providing me access to the DbContext methods through the Instance property getter without having to add methods needed from the DbContext class to the interface.

Until now, this works great.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow