存储库模式,使用泛型的工作单元

本文关键字:泛型 工作 单元 模式 存储 | 更新日期: 2023-09-27 17:58:56

我有以下代码(为了简化起见,我已经提交了某些区域)

public interface ICustomer
{
    int Age { get; set; }
    string Name { get; set; }
}
public class Customer : ICustomer
{
    public int Age { get; set; }

    public string Name { get; set; }
}
public interface ICustomerRepository<T> where T : class
{
    IEnumerable<T> GetCustomers();
    T GetCustomer();
    void AddCustomer(T customer);
}
public class CustomerRepository<T> : ICustomerRepository<T> where T:class 
{
    public IEnumerable<T> GetCustomers()
    {
        return new List<T>();
    }

    public T GetCustomer()
    {
        return null;
    }

    public void AddCustomer(T customer)
    {
    }
}

public class UnitOfWork //: IUnitOfWork
{
    public ICustomerRepository<ICustomer> CusRepo
    {
        get
        {
            return new CustomerRepository<Customer>();
            //Error: Error  1   Cannot implicitly convert   type 'ConsoleApplication1.CustomerRepository<ConsoleApplication1.Customer>' to 'ConsoleApplication1.ICustomerRepository<ConsoleApplication1.ICustomer>'. An explicit conversion exists (are you missing a cast?)    
        }
    }
}

我在UnitOfWork类中得到以下错误。我该如何解决这个问题?

错误1无法将类型"ConsoleApplication1.CustomerRepository"隐式转换为"ConsoleAApplication1.ICustomerRepository"。存在显式转换(是否缺少强制转换?)

我不能使用协方差,因为该参数同时用于输入和输出目的。

存储库模式,使用泛型的工作单元

您应该返回如下存储库:

get
{
    return new CustomerRepository<ICustomer>();
}

不能在此处使用方差,因为ICustomerRepository<T>在输入和输出位置都有通用参数。要使用方差,可以将ICustomerRepository<T>拆分为两个独立的接口,如以下所示:

interface IReadRepository<out T>
{
    IEnumerable<T> GetItems();
    T GetItem(int id);
}
interface IWriteRepository<in T>
{
    void AddItem(T item);
}

我已经在您的示例代码中重构了模式。

public class Customer
{
    public int Age { get; set; }
    public string Name { get; set; }
}
public interface IUnitOfWork
{
    int Save();
}
public interface IBaseRepository<TEntity, TKey> : IUnitOfWork where TEntity : class
{
    void Add(TEntity entity);
    TEntity Find(TKey id);
    IEnumerable<TEntity> GetAll();
}

public interface ICustomerRepository :IBaseRepository<Customer, int>
{
}
public class CustomerRepository : ICustomerRepository
{
    public void Add(Customer entity)
    {
        throw new System.NotImplementedException();
    }
    public Customer Find(int id)
    {
        throw new System.NotImplementedException();
    }
    public IEnumerable<Customer> GetAll()
    {
        throw new System.NotImplementedException();
    }
    public int Save()
    {
        throw new System.NotImplementedException();
    }
}

public class UnitOfWork : IUnitOfWork
{
    private ICustomerRepository _customers;
    public ICustomerRepository Customers
    {
        get { return _customers; }
    }
    public UnitOfWork()
    {
        _customers = new CustomerRepository();
    }
    public int Save()
    {
        throw new System.NotImplementedException();
    }
}