【发布时间】:2021-01-09 08:41:43
【问题描述】:
我在使用服务集合时遇到以下错误:
验证服务描述符“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);
}
}
【问题讨论】:
-
请出示
EFCoreCountryRepository的代码。
标签: asp.net-core dependency-injection repository-pattern