How would I design a repository to handle multiple data access strategies?

别等时光非礼了梦想. 提交于 2020-01-12 06:24:18

问题


What would a skeleton design look like for a repository able to support multiple database layers using ASP.NET MVC and C#? I want to see what a design would look like if I support both LINQ to SQL and NHibernate. How would I create my database object, and call a method on it in my BLL layer?


回答1:


The repository pattern is probably the best solution for this. You would define an interface for each repository, then create concrete repositories for Linq2Sql and NHibernate implementations, e.g.

public interface ICustomerRepository
{
    Customer GetCustomer(int id);
}

public class NhibCustomerRepository : ICustomerRepository
{
    public Customer GetCustomer(int id)
    {
        // NHibernate implementation
    }
}

public class LtsCustomerRepository : ICustomerRepository
{
    public Customer GetCustomer(int id)
    {
        // Linq2Sql implementation
    }
}

A dependency injection framework, such as Ninject, makes it easy to dynamically switch between implementations. You may have to do some extra dependency injection with NHibernate to pass the current ISession into your repositories so that they participate in the same unit-of-work.




回答2:


I allready responded that twice xD

one here

Reposity pattern using linq

another here

ControllerFactory having controllers separated in a different project



来源:https://stackoverflow.com/questions/1079378/how-would-i-design-a-repository-to-handle-multiple-data-access-strategies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!