简体   繁体   中英

Register generic EntityFrameworkCore DbContext in ASP.Net Core 1.0

I am trying to use generic DbContext in ASP.Net Core 1.0 however I am getting following error:

ArgumentException: Type 'idmin.data.IdminDataContext`1[System.Int32]' does not have a default constructor Parameter name: type 

Here is how IdminDataContext is defined:

public class IdminDataContext<TKey> : DbContext where TKey : IEquatable<TKey>
{

    public IdminDataContext(DbContextOptions<IdminDataContext<TKey>> options) : base(options)
    {
    }

    public DbSet<Idmin.Models.Client<TKey>> Clients { get; set; }
}

and here is how I am registering it in startup class.

public void ConfigureServices(IServiceCollection services)
{
    var connection = "my connection string";
    services.AddDbContext<IdminDataContext<int>>(options => options.UseSqlServer(connection));

    services.AddMvc();
}

I tried adding default constructor in IdminDataContext class but it didn't help. Any idea what am I missing here?

I found issue. It was silly mistake on my part. Instead of using constructor injection in Controller I was using action method injection which was causing exception in Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder's CreateModel method. Fixed this issue by moving dependency injection to constructor instead of action method injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM