【问题标题】:Remove coupling between Data Access layer and UI layer消除数据访问层和 UI 层之间的耦合
【发布时间】:2020-03-06 22:51:45
【问题描述】:

我想为 Windows 应用程序设计一个 n 层架构。我想消除 UI 层和数据访问层之间的耦合。换句话说,我希望 UI 层只依赖于业务逻辑层。

我的例子:

public Class Person
{
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
}

在数据访问层,我在 UI 层创建了新的 Person,但我不会调用数据访问层。最好的方法是什么?

谢谢

【问题讨论】:

    标签: c# architecture n-tier-architecture


    【解决方案1】:

    对于开发 Windows 应用程序并将 UI 与数据访问层解耦,最好使用 MVVM 模式,请参阅说明here

    MVVM 它允许将 UI 与模型分离,但为了将数据访问逻辑与业务逻辑分离,您需要拆分模型,我建议使用域驱动设计 (DDD),您可以阅读它here

    并使用像 Entity Framework 这样的 ORM

    你应该关注Persistence Ignorance Principle

    您的示例可能如下: 在域业务逻辑层中,您将拥有

        //Domain Business layer logic
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
    
    interface IPersonRepository
    {
        IEnumerable<Person> GetAll();
    
        void Update(Person person);
    }
    

    在应用层

        //Application logic
    class PersonViewModel
    {
        private readonly IPersonRepository _personRepository;
    
        public PersonViewModel(IPersonRepository personRepository)
        {
            _personRepository = personRepository;
        }
    
        public ObservableCollection<Person> Persons
        {
            get { return new ObservableCollection<Person>(_personRepository.GetAll()); }
        }
    }
    

    在数据访问中,您将拥有 IPersonRepository 的实现

        //Data Access layer Persistance logic
    class PersonRepository : IPersonRepository
    {
        public IEnumerable<Person> GetAll()
        {
            // ORM Implementation here
    
            return new List<Person>();
        }
    
        public void Update(Person person)
        {
          // Update logic here
        }
    }
    

    应用层和数据访问层应该依赖于领域层,数据访问逻辑对应用层一无所知

    【讨论】:

      【解决方案2】:

      您可以将MVC - Model View Controller 设计模式与DAO - Data Acess Object 设计模式结合使用。

      MVC 会将您的 UI(用户界面)与业务逻辑和模型(数据)分离,在模型内部,您可以使用 DAO 模式提供的界面来访问数据。

      【讨论】:

        猜你喜欢
        • 2012-11-27
        • 1970-01-01
        • 2011-02-17
        • 2010-12-14
        • 2010-09-16
        • 2011-03-05
        • 2014-11-19
        • 2021-02-11
        • 2013-05-27
        相关资源
        最近更新 更多