![](/img/trans.png)
[英]ASP.NET Core 2 Unable to resolve service for type Microsoft EntityFrameworkCore DbContext
[英]Register generic EntityFrameworkCore DbContext in ASP.Net Core 1.0
我正在嘗試在ASP.Net Core 1.0
使用通用DbContext,但是出現以下錯誤:
ArgumentException: Type 'idmin.data.IdminDataContext`1[System.Int32]' does not have a default constructor Parameter name: type
這是IdminDataContext的定義方式:
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; }
}
這是我在啟動類中注冊它的方式。
public void ConfigureServices(IServiceCollection services)
{
var connection = "my connection string";
services.AddDbContext<IdminDataContext<int>>(options => options.UseSqlServer(connection));
services.AddMvc();
}
我嘗試在IdminDataContext類中添加默認構造函數,但沒有幫助。 知道我在這里想念什么嗎?
我發現了問題。 我這是愚蠢的錯誤。 我沒有在Controller中使用構造函數注入,而是使用了操作方法注入,這導致Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder的CreateModel方法引起異常。 通過將依賴項注入移至構造函數而不是動作方法注入來解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.