Asp.net core中使用具有多种类型<T,T>的泛型Repository

问题描述

Registering repository using generics with multiple types <T, T> c# dotnet core

我正在创建一个通用存储库,如下所示:

public interface IRepository<T> where T : class
  {
    Task<T> GetById(int id);
    Task Add(T entity);
    void AddRange(IEnumerable<T> entities);
    Task<int> Save();
    Task Delete(int id);
    void Delete(T entity);
    T Update(T entity);

  }

  public abstract class Repository<T, TContext> : IRepository<T> where T :
  class where TContext : DbContext
  {
    protected readonly TContext _context;
    private DbSet<T> _table;
    protected Repository(TContext context)
    {
      _context = context;
      _table = _context.Set<T>();
    }
    // implementation
   }

我想将任何 DBcontext 传递给实现,具体的实现应该是这样的:

public interface ICouponRepository : IRepository<Coupon>
  {
    Task RedeemCoupon(int id, Guid userId);
  }

  public class CouponRepository : Repository<Coupon, CouponApiDBContext>, ICouponRepository
  {
    private readonly CouponApiDBContext _couponApiDBContext;

    protected CouponRepository(CouponApiDBContext couponApiDBContext) : base(couponApiDBContext)
    {
      _couponApiDBContext = couponApiDBContext;
    }

    public Task RedeemCoupon(int id, Guid userId)
    {
      throw new NotImplementedException();
    }
  }

然后我按如下方式注册这两项服务:

 services.AddTransient(typeof(IRepository<>), typeof(Repository<,>))
              .AddTransient<ICouponRepository, CouponRepository>()

但是我可以实例化通用存储库,但出现以下错误:

An unhandled exception of type 'System.ArgumentException' occurred in xxx.dll: 'Cannot instantiate implementation type 'xxx.Repositories.Repository2[T,TContext]' for service type 'xxx.Repositories.IRepository1[T]'.'

答案

立即想到三件事。

第一个与您的问题无关,但 CouponRepository 不应该有自己的 _couponApiDBContext 成员,它可以访问基类 TContext - 这就是首先让它通用的全部意义。

第二个是您在 ICouponRepository 中使用 RedeemCoupon 方法专门化了 IRepository<Coupon> - 因此您注册开放泛型类型的机会为零,只是期望 DI 知道您所追求的实际接口。

您只剩下删除此 AddTransient(typeof(IRepository<>), typeof(Repository<,>)) - 这是毫无意义的,因为 DI 无论如何都无法实例化抽象类,这是错误消息的根本原因,您应该注册 AddTransient<ICouponRepository, CouponRepository>() 并在您需要的地方请求 ICouponRepository - 您不能请求 IRepository<Coupon> 因为它没有我认为您需要的 RedeemCoupon 方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值