POO and Interface (in C#)

2019-09-08 12:19发布

I need to understand Interface :

I have this structure :

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

For example, i have an Interface Core.IVehicle who describe a basic vehicle like :

Color
Speed

And a one method :

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

In my BLL, I have an object "BLL.Car" who implement "Core.IVehicle". So, i will have a LoadVehicle method and access to DALfor get basics informations

But DAL need to return an object "BLL.Car" implemented. But i can't make a reference to BLL because of Circular Dependencies.

What i've miss? How my DAL can return an object "BLL.Car" implemented?

1条回答
放荡不羁爱自由
2楼-- · 2019-09-08 12:38

But DAL need to return an object "BLL.Car" implemented.

This is probably where the confusion lies.

Your DAL should not return the BLL version of Car, the DAL should have it's own version of Car aka entity / DAO (data access object). The BLL should query the DAL for the car "entity" (whether it be returned as a DTO or an IVehicle) and construct it's own representation of Car aka Domain Model.

So to summarise you should have 2 (or 3 if you want a view model as well) versions of Car i.e.

Entity/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;
    }
}

Domain Model (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 (View)

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

Because IVehicle is in the Core DLL it can be shared across all your layers, so you don't need to worry about circular references, and it gives you a consistent return type.

查看更多
登录 后发表回答