【问题标题】:Generic type not resolving by DI in .NET CORE.NET CORE 中的 DI 无法解析的泛型类型
【发布时间】: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


【解决方案1】:

您可能想让GenericRepository 实现接口,但您对T 进行了约束。你想要的

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

没有

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多