具有通用参数的asp.net核心中的依赖项注入

时间:2020-09-23 07:25:58

标签: asp.net-core dependency-injection repository-pattern

在使用服务收集过程中出现以下错误:

验证服务描述符'ServiceType时出错: HappinessMeter.BL.GenericBL.IGenericBL'1 [HappinessMeter.Entity.Models.MCountry] 生命周期:单例实施实例: HappinessMeter.BL.EFCoreCountryBL':类型的常数 'HappinessMeter.BL.EFCoreCountryBL'无法转换为服务类型 'HappinessMeter.BL.GenericBL.IGenericBL`1 [HappinessMeter.Entity.Models.MCountry]'

Startup.cs

services.Add(new ServiceDescriptor(typeof(IGenericBL<MCountry>), 
  new EFCoreCountryBL(new EFCoreCountryRepository(context))));
services.Add(new ServiceDescriptor(typeof(IGenericBL<User>),  
   new EFCoreUserBL(new EFCoreUserRepository(context))));

我用于EFCoreRepository的代码是:

public class EFCoreRepository<Tentity, Tcontext> : IRepository<Tentity> where Tentity : class where Tcontext : DbContext
    {
        public readonly Tcontext context;
        public EFCoreRepository(Tcontext _context)
        {
            context = _context;
        }
        public async Task<Tentity> Add(Tentity entity)
        {
            context.Set<Tentity>().Add(entity);
            await context.SaveChangesAsync();
            return entity;
        }

        public async Task<Tentity> Delete(long id)
        {
            var entity = await context.Set<Tentity>().FindAsync(id);
            if (entity == null)
            {
                return entity;
            }

            context.Set<Tentity>().Remove(entity);
            await context.SaveChangesAsync();

            return entity;
        }

        public async Task<Tentity> Get(long id) => await context.Set<Tentity>().FindAsync(id);

        public async Task<List<Tentity>> GetAll() => await context.Set<Tentity>().ToListAsync();

        public async Task<Tentity> Update(Tentity entity)
        {
            context.Entry(entity).State = EntityState.Modified;
            await context.SaveChangesAsync();
            return entity;
        }
    }

和EFCoreCountryRepository是

public class EFCoreCountryRepository : EFCoreRepository<MCountry, HMDEVContext>
    {
        public EFCoreCountryRepository(HMDEVContext context) : base(context)
        {

        }
        public async Task<MCountry> GetByAlpha(string alpha)
        {
            return await  context.MCountry.FirstOrDefaultAsync(x => x.Alpha2Code == alpha);
        }

    }

1 个答案:

答案 0 :(得分:0)

错误说:EFCoreCountryBL无法转换为IGenericBL1<MCountry>

您的类型不匹配或缺少隐式或显式转换。