.NET CORE中的DI不解析通用类型

Chi*_*mar 0 c# .net-core asp.net-core

我有一个简单的通用存储库,它采用类型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>();
    }
Run Code Online (Sandbox Code Playgroud)

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;
        }}
Run Code Online (Sandbox Code Playgroud)

在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" });
            });
        }
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

V0l*_*dek 5

你可能想要GenericRepository实现接口,但是你做了一个约束T.你要

public class GenericRepository<T> : IGenericRepository<T> where T : class
Run Code Online (Sandbox Code Playgroud)

public class GenericRepository<T> : where T : class, IGenericRepository<T>
Run Code Online (Sandbox Code Playgroud)