Shahar Shokrani
Shahar Shokrani

Reputation: 8762

How to properly configure the `services.AddDbContext` of `ConfigureServices` method

I'm trying to run an .NET Core Web application with EF Core. In order to test the repository I've added an MyDbContext that inherits the EF DbContext and interface IMyDbContext.

public interface IMyDbContext
{
    DbSet<MyModel> Models { get; set; }
}

public class MyDbContext : DbContext, IMyDbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    public virtual DbSet<MyModel> Models { get; set; }
}

The context interface is injected to my generic repository:

public class GenericRepository<TEntity> : IGenericRepository<TEntity>
{
    private readonly IMyDbContext _context = null;

    public GenericRepository(IMyDbContext context)
    {
        this._context = context;
    }
}

When I use this code (without the interface) on startup.cs:

services.AddDbContext<MyDbContext>(options =>
     options.UseSqlServer(...));

I'm getting a run-time error of:

InvalidOperationException: Unable to resolve service for type 'IMyDbContext' while attempting to activate 'GenericRepository`1[MyModel]'

And when using this line of code:

services.AddDbContext<IMyDbContext>(options =>
     options.UseSqlServer(...));

I'm getting this compiled time error code of:

Cannot convert lambda expression to type 'ServiceLifetime' because it is not a delegate type

My question is how to properly configure the services.AddDbContext of ConfigureServices method? (Is there any changes needed inside Configure method?) If needed I'm willing to modify the IMyDbContext

Upvotes: 12

Views: 66225

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205789

Use one of the overloads having 2 generic type arguments, which allow you to specify both the service interface/class you want to register as well as the DbContext derived class implementing it.

For instance:

services.AddDbContext<IMyDbContext, MyDbContext>(options =>
     options.UseSqlServer(...));

Upvotes: 12

Shahar Shokrani
Shahar Shokrani

Reputation: 8762

Just found the answer:

I was missing the adding of the scope between IMyDbContext and MyDbContext.

public void ConfigureServices(IServiceCollection services)
{                    
    services.AddDbContext<MyDbContext>(options => options.UseSqlServer(...));
    services.AddScoped<IGenericRepository<MyModel>, GenericRepository<MyModel>>();
    services.AddScoped<IMyDbContext, MyDbContext>();
}

Upvotes: 7

Related Questions