ASP.NET存储库设计模式

本文关键字:设计模式 存储 NET ASP | 更新日期: 2023-09-27 17:58:23

这是我在ASP中使用的当前设计模式。NETweb应用程序,我见过有人使用存储库,但我没有实现存储库设计模式。

有人能指出我如何在设计中实现存储库模式吗?以及如果我在我的案例中实现一个存储库,我会得到什么样的好处。

此外,我应该在设计中实现的接口有什么好的利用吗?

客户类别(Customer.cs)

public class Customer
{
    public int CustomerID { get; set; }
    public string Name { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

DBManager类(DBManager.cs)

public class DBManager
{
    private const string connectionString = "some connection string";
    public static IEnumerable<Customer> getAllCustomers()
    {
        List<Customer> cust = new List<Customer>();
        try
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                string cmdText = "SELECT * FROM Customer";
                SqlCommand comm = new SqlCommand(cmdText, conn);
                SqlDataReader dr = comm.ExecuteReader();
                while (dr.Read())
                {
                    cust.Add(new Customer 
                    {
                        CustomerID = int.Parse((string)dr["customerID"]),
                        Name = (string)dr["name"],
                        Address1 = (string)dr["address1"],
                        Address2 = (string)dr["address2"]
                    });
                }
            }
        }
        catch (SqlException e)
        {
            throw e;
        }
        return cust;
    }
}

索引页代码隐藏(Index.aspx.cs)

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        IEnumerable<Customer> cust = DBManager.getAllCustomers();
        // some codes to display IEnum customers in page
    }
}

ASP.NET存储库设计模式

在您的案例中,DBManager本身非常接近存储库模式。在领域驱动设计的世界里,通常会为你找到你的领域的每个聚合根创建一个存储库,正如Martin Fowler所解释的那样

http://martinfowler.com/bliki/DDD_Aggregate.html

对于您在域中处理的每个实体/聚合根,您将创建一个存储库,用于处理CRUD操作(创建、读取、更新和删除)。因此,在您的情况下,您可以拥有一个客户存储库。

编辑:其好处是,数据的触摸方式及其工作方式的实现是从代码的其余部分中抽象出来的。然后,您可以简单地调用存储库中的方法,使代码更易于阅读。此外,如果您将存储库实现为一个接口,您可以开始使用依赖注入之类的东西,这将使您的代码更易于维护、测试和其他*属性。;-)

C#中一个典型的Repository接口看起来是这样的(显然,根据您的需要可能会有所不同

public interface ICustomerRepository : IDisposable
{
    IEnumerable<Customer> GetCustomers();
    Customer GetCustomerByID(int customerId);
    void InsertCustomer(Customer customer);
    void DeleteCustomer(int customerId);
    void UpdateCustomer(Customer customer);
    void Save();
}

可以在MSDN上找到一个很好的资源来了解更多关于这方面的信息。该示例使用MVC和实体框架,但显然可以根据您的应用程序进行调整

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application