如何解决具有通用参数的asp.net核心中的依赖项注入
在使用服务收集过程中出现以下错误:
验证服务描述符'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);
}
}
解决方法
错误说:EFCoreCountryBL
无法转换为IGenericBL1<MCountry>
您的类型不匹配或缺少隐式或显式转换。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。