我如何设计存储库来处理多种数据访问策略?

时间:2009-07-03 13:33:03

标签: c# nhibernate linq-to-sql design-patterns repository-pattern

对于能够使用ASP.NET MVC和C#支持多个数据库层的存储库,骨架设计会是什么样子?我希望看到如果我支持LINQ to SQL和NHibernate,设计会是什么样子。我如何创建我的数据库对象,并在我的BLL层中调用它的方法?

2 个答案:

答案 0 :(得分:8)

repository pattern可能是最好的解决方案。您将为每个存储库定义一个接口,然后为Linq2Sql和NHibernate实现创建具体的存储库,例如。

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
    }
}

依赖注入框架(例如Ninject)可以轻松地在实现之间动态切换。您可能需要使用NHibernate进行一些额外的依赖注入,以将当前的ISession传递到您的存储库中,以便它们参与相同的工作单元。

答案 1 :(得分:0)