Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject 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<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?

like image 389
Miguel Moura Avatar asked Apr 12 '16 20:04

Miguel Moura


1 Answers

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.

like image 95
Claus Nielsen Avatar answered Oct 05 '22 13:10

Claus Nielsen