【问题标题】:POO and Interface (in C#)POO 和接口(在 C# 中)
【发布时间】:2013-12-09 02:07:12
【问题描述】:

我需要了解接口:

我有这个结构:

Core (contain Interface)
BLL (Contain object who implement interface 
DAL (Contain Data access)
IHM (Call BLL object)

例如,我有一个接口 Core.IVehicle,它描述了一个基本的车辆,例如:

Color
Speed

还有一种方法:

LoadVehicle(int id) //return a iVehicule with speed and color

在我的 BLL 中,我有一个实现“Core.IVehicle”的对象“BLL.Car”。 所以,我将有一个 LoadVehicle 方法并访问 DAL 以获取基本信息

但是 DAL 需要返回一个实现的对象“BLL.Car”。但由于循环依赖,我无法引用 BLL。

我错过了什么?我的 DAL 如何返回实现的对象“BLL.Car”?

【问题讨论】:

  • poco .. 普通的旧 clr 对象
  • 我认为你的意思是 OOP 面向对象编程
  • 你的 DAL 应该返回 BLL.Car 实施是什么意思?你的意思是你的 DAL 应该返回一个 BLL 对象,它的所有属性都是从数据库中填充的?
  • 阅读这个问题可能会有所帮助stackoverflow.com/questions/1042114/…
  • @FaddishWorm 意大利语 oop 面向对象编程 -> POO Programmazione Orientata agli Oggetti。我想在法国是类似的东西

标签: c# oop interface dependency-injection


【解决方案1】:

但是 DAL 需要返回一个实现的对象“BLL.Car”。

这可能是混乱所在。

你的 DAL不应该返回 Car 的 BLL 版本,DAL 应该有它自己的 Car 版本,也就是 entity / DAO em>(数据访问对象)。 BLL 应向 DAL 查询汽车“实体”(无论是作为 DTO 还是 IVehicle 返回)并构建它自己的 Car 即域模型表示。

所以总结一下,你应该有 2 个(或者如果你想要一个视图模型,也可以有 3 个)版本的Car

实体/DAO (DAL)

public class Car : IVehicle
{
}
...
public class CarRepository
{
    ...
    public IVehicle LoadVehicle(int id)
    {
        var entity = // query DB for instance of DAL.Car
        return entity;
    }
}

域模型 (BLL)

public class Car : IVehicle
{
}
...
public class CarService
{
    public IVehicle FindCarById(int id)
    {
        var repo = new DAL.CarRepository(...);
        var carEntity = repo.LoadVehicle(id); // returns DAL.Car instance 
        return new BLL.Car // we turn DAL.Car into our DLL.Car
        {
            Color = carEntity.Color,
            Speed = carEntity.Speed
        };
    }
}

IHM(视图)

public class Controller
{
    public void ViewCarDetails(int id)
    {
        var carService = new BLL.CarService();
        var car = carService.FindCarById(id);
        // populate UI with `car` properties
    }
}

因为IVehicle 位于核心 DLL 中,它可以在所有层之间共享,因此您无需担心循环引用,它为您提供一致的返回类型。

【讨论】:

  • @Steven 如果你想实现一个纯粹的分层架构,那么是的。像AutoMapper 这样的库让这个平凡的任务变得非常简单。我理解 Mark 试图提出的观点(我之前读过那篇文章)但是,对我来说,保持你的域独立于 UI 和 DAL 仍然是一个好习惯,因为,让我们面对现实吧,应用程序会不断发展,无论你多么确定是事情不会改变 - 没有人可以预测未来。所以问题真的变成了现在分离你的层而不是以后必须重构是否值得?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 2011-07-31
相关资源
最近更新 更多