【发布时间】:2018-10-07 05:45:51
【问题描述】:
我有一个简单的通用存储库,它采用类型 T,T 被限制为一个类。非常直接的东西,但 .NET Core 无法满足依赖关系。不确定,我做错了什么。
错误:
System.ArgumentException: GenericArguments[0], 'Building.Manager.Domain.Society', on 'Building.Manager.Repository.GenericRepository`1[T]'
violates the constraint of type 'T'. ---> System.TypeLoadException: GenericArguments[0], 'Building.Manager.Domain.Society', on 'Building
.Manager.Repository.GenericRepository`1[T]' violates the constraint of type parameter 'T'.
public class Society : BaseEntity
{
public string Name { get; set; }
public string Phone { get; set; }
public Address Address { get; set; }
public IEnumerable<Flat> Flats { get; set; }
public Society() => this.Flats = new List<Flat>();
}
BaseEntity 是一个带有受保护构造函数的简单抽象类。
public interface IGenericRepository<T> where T : class
{}
public class GenericRepository<T> where T : class, IGenericRepository<T>
{
private readonly DbContext _context;
protected GenericRepository() { }
public GenericRepository(DbContext context)
{
this._context = context;
}}
在 StartUp.cs 上配置方法如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<DbContext, ApplicationDbContext>();
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped<ISocietyService, SocietyService>();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Building Manager API", Version = "v1" });
});
}
感谢您的帮助。
【问题讨论】:
-
T 是类类型还是 IGenericRepository
?你可能是想说: public class GenericRepository : IGenericRepository where T : class 而不是 where T : class, IGenericRepository ?
标签: c# asp.net-core .net-core