c# - 如何使用存储库模式和工厂方法模式组织我的类/接口(interface)?

标签 c# design-patterns repository-pattern factory

我正在创建一个示例应用程序来一起理解存储库和工厂方法模式,因为将在更大的项目中使用。

我想要实现的是能够使网站与不同的 ORM 工具一起使用。

例如,网站将实现 LINQ to SQL 和 Ado Entity Framework 工作类,然后使用工厂方法将使用这些 ORM 之一“使用配置值”来加载存储库对象中的数据。

到目前为止我得到的内容如下

interface IRepository : IDisposable
{
  IQueryable GetAll();  
}

interface ICustomer : IRepository
{
}

public class CustomerLINQRepository : ICustomer
{
    public IQueryable GetAll()
    {
       // get all implementation using linqToSql
    }
    public void Dispose()
    {
      throw;
    }
    public IRepository GetObject()
    {
        return this;
    }
}


public class CustomerADORepository : ICustomer
{
    public IQueryable GetAll()
    {
       // get all implementation using ADO
    }
    public void Dispose()
    {
      throw new NotImplementedException();
    }
    public IRepository GetObject()
    {
        return this;
    }
}


// Filling a grid with data in a page
IRepository customers = GetCustomerObject();
this.GridView1.DataSource = customers.GetAll();
this.GridView1.DataBind();
////

public IRepository GetCustomerObject()
{
    return new CustomerLINQRepository(); // this will return object based on a config value later
}

但是我感觉有很多设计错误希望你能帮我解决,以获得更好的设计。

最佳答案

我的两分钱:

A.我会添加通用基础存储库类。无论类型是什么,许多存储库操作都是相同的。它可以节省您大量的打字时间。

B.我不明白为什么您的存储库要实现 ICustomer 接口(interface)。 数据对象的接口(interface)是一个很好的实践,但我认为您的存储库不应该实现它。

C.如果您的数据对象有一个通用的实现,我将为它们创建一个基类,并将存储库限制为仅适用于该类型的派生类。

我会做类似的事情:

public interface IEntity
{
     // Common to all Data Objects
}

public interface ICustomer : IEntity
{
     // Specific data for a customer
}


public interface IRepository<T, TID> : IDisposable where T : IEntity
{
     T Get(TID key);
     IList<T> GetAll();
     void Save (T entity);
     T Update (T entity);

     // Common data will be added here
}

public class Repository<T, TID> : IRepository<T, TID>
{
     // Implementation of the generic repository
}

public interface ICustomerRepository
{
     // Specific operations for the customers repository
}

public class CustomerRepository : Repository<ICustomer, int>, ICustomerRepository
{
     // Implementation of the specific customers repository
}

用法:

CustomerRepository repository = new CustomerRepository();
IList<ICustomer> customers = repository.GetAll();
// Do whatever you want with the list of customers

这就是我使用 NHibernate 实现 DAL 的方式。您可以在“NHibernate in Action”中找到该用法的一些变化。

我还建议按照 Matt 的建议使用某种 IoC Controller 。

关于c# - 如何使用存储库模式和工厂方法模式组织我的类/接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1490436/

相关文章:

c# - .NET 在异步任务完成之前返回响应

c# - 等待任何线程完成,而不是全部

design-patterns - 这种反模式/代码气味有名字吗?

c# - Entity Framework : Insert foreign key rows when Update table

c# - 使用 MVC + 存储库模式,业务逻辑应该在哪里?

c# - 我的服务和存储库层的职责

c# - 没有其他验证的验证摘要

c# - 从 C++ 包装代码以在 C# 中使用

c++ - 对基于 I/O 的对象执行一系列操作的设计模式

ios - 在 UITableViewCell 和 UICollectionViewCell 之间共享代码