我如何设计一个存储库来处理多个数据访问策略? [英] How would I design a repository to handle multiple data access strategies?

查看:144
本文介绍了我如何设计一个存储库来处理多个数据访问策略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

存储库模式可能是最好的解决方案。您将为每个存储库定义一个接口,然后为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传递到您的存储库,以便他们参与相同的工作单元。


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?

解决方案

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.

这篇关于我如何设计一个存储库来处理多个数据访问策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆