如何处理业务对象之间的依赖关系

时间:2013-12-17 13:34:36

标签: c# .net

如果之前有人问过道歉,我找不到类似的问题,所以我只能假设我的术语有误!

无论如何,我想知道如何处理业务层对象之间的依赖关系。假设我有两个业务对象:

轮式服务

public class WheelService : IWheelService
{
    private IWheelRepository Repository { get; set; }

    public WheelService(IWheelRepository repository)
    {
        this.Repository = repository;
    }

    public Wheel Get(int id) { ... }
}

汽车服务

public class CarService : ICarService
{
    private ICarRepository Repository { get; set; }

    public CarService(ICarRepository repository)
    {
        this.Repository = repository;
    }

    public void Create(Car newCar)
    {
        // I need to access functions from the WheelService here
    }
}

你会使用什么样的架构来让我以松散耦合的方式从一个业务对象中调用一个业务对象的方法,这也很适合TDD?

2 个答案:

答案 0 :(得分:2)

只需在构造函数中添加存储库依赖项的方式添加它们:

public CarService(ICarRepository repository, IWheelService wheelservice)
{
    ...
}

答案 1 :(得分:0)

您还可以使用Builder模式,如果您有许多依赖项,这将非常有用

public class CarService : ICarService
{
    private ICarRepository Repository { get; set; }
    private IWheelService WheelService { get; set; }

    public CarService(ICarRepository repository)
    {
        this.Repository = repository;
    }

    public ICarService WithWheelService(IWheelService service)
    {
        // do arguments check
        if(service == null) throw ...;

        WheelService = service;
        return this;
    }
    public Car Build()
    {
        return new Car(WheelService, ...);        
    }
}

以下是用法

ICarService carService = new CarService();
IWheelService wheelService = new WheelService();
...    
carService.WithWheelService(wheelService)
          .WithSomethingElse(somethingElse)
          .WithLights(brightLights)
          .UsingMainColour(selectedColour);
var car = carService.Build()

见这些行

ICarService carService = new CarService();
IWheelService wheelService = new WheelService();

您可以在此处使用IoC容器来解析所需的类。