类型上的构造函数找不到 .NET Core



我 create.NET 核心API,然后我决定创建存储库,因此创建具有接口和实现的DataAccessLayer。

public class GappedData : IGappedData
{
private readonly GappedContext context;
private readonly IDictionary<Type, object> repositories;
public GappedData(GappedContext context)
{
this.context = context;
this.repositories = new Dictionary<Type, object>();
}
public IRepository<ApplicationUser> ApplicationUser => this.GetRepository<ApplicationUser>();
private IRepository<T> GetRepository<T>() where T : class
{
var type = typeof(T);
if (!this.repositories.ContainsKey(type))
{
var typeOfRepository = typeof(IRepository<T>);
var repository = Activator.CreateInstance(typeOfRepository, this.context);
this.repositories.Add(type, repository);
}
return (IRepository<T>)this.repositories[type];
}
}

所以当我尝试调用它时会抛出异常

未找到类型'Gapped.DataAccessLayer.Interfaces.IRepository'1[[Gapped.Entities.Models.ApplicationUser.ApplicationUser, Gapped.Entities, version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' 上的构造函数。

您正在尝试在此处创建接口的实例:

var typeOfRepository = typeof(IRepository<T>);
var repository = Activator.CreateInstance(typeOfRepository, this.context);

您收到该错误是因为接口没有构造函数。

改为将typeof(IRepository<T>)更改为具体实现typeof。(就像typeof(Repository<T>)一样,如果Repository<T>实现了IRepository<T>接口。

最新更新