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

前端 未结 1 996
甜味超标
甜味超标 2021-02-11 09:42

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 supp

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-11 10:31

    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.

    0 讨论(0)
提交回复
热议问题