.NET CORE中的通用类型不能由DI解决

时间:2018-10-06 20:24:41

标签: c# asp.net-core .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>();
    }

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" });
            });
        }

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

您可能想使GenericRepository实现该接口,但是您对T进行了限制。你想要

public class GenericRepository<T> : IGenericRepository<T> where T : class

不是

public class GenericRepository<T> : where T : class, IGenericRepository<T>