Repository Pattern in Layered Architecture

2019-04-13 17:08发布

问题:

I've gone through quite a few articles on the repository pattern and had some questions. I'm trying to implement this in a ASP.NET 4.0 application. The architecture is a layered architecture with a Presentation Layer, Business Layer and Data Layer. From this article, http://www.primaryobjects.com/CMS/Article108.aspx

I have created the MYSQLRepository (DataLayer)

public class MySQLRepository:IOrderRepository
{
    public List<Order> GetOrders()
    {

        List<Order> orders = new List<Order>();
        orders.Add(new Order(1,"A"));
        orders.Add(new Order(2,"B"));

        return orders;
    }
}

My Business Layer looks like this

public class OrderBL
{
    IOrderRepository orderrep;
    public OrderBL(IOrderRepository repository)
    {
       orderrep = repository;

    }

    public List<Order> GetOrders()
    {
        return orderrep.GetOrders();

    }
}

Now my question is that in the presentation layer, I'm expected to do this

protected void Page_Load(object sender, EventArgs e)
{
    OrderBL orderBL = new OrderBL(new MySQLRepository());
    List<Order> orders = orderBL.GetOrders();

    foreach (Order order in orders)
    {
        Response.Write(order.OrderId.ToString() + ". " + order.OrderNo + "<br>");
    }

}

In order to do this, I have to reference my DataLayer in the presentation layer. Isn't that wrong? Ideally I would only want to reference my Business Layer. IS something wrong in my implementation or is it not the right place to implement the pattern. I have seen many examples using ASP.NET MVC and it seems to work well there.

Also, Do i really need dependency injection here?

Thanks for the help Soni

回答1:

it's better to unilize IoC to get constructor injection, this will remove unnecessary layers' references.



回答2:

I think you're missing the point and the reason why the repository pattern is so powerful. It may seem strange to call it in your presentation layer, but imagine that page needed to use a different datasource. You can just as easily swap it out with a call like: orderBL orderBL = new OrderBL(new OracleRepository());



回答3:

Another alternative here is you don't pass repository references around.

Your BL can instantiate the DL when it needs to. If you have cross method calls where several operations need to happen in data then use a facade layer to sit on top of your business objects. Either way then you don't need a direct reference to a data layer repository from your presentation layer. If it makes you feel even better, pull any of your Model classes (for example Order) out into a separate "Models" project.



回答4:

To avoid calling the data layer directly, you could call a function in your business layer to instatiate your repository. Your business layer could take care of the rest.