У меня есть простой репозиторий Generic, который принимает тип 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" });
});
}
Спасибо за вашу помощь.