如何处理业务对象之间的依赖关系
本文关键字:之间 对象 依赖 关系 业务 何处理 处理 | 更新日期: 2024-10-30 18:43:32
抱歉,如果之前有人问过这个问题,我找不到类似的问题,所以我只能假设我的术语是错误的!
无论如何,我想知道如何处理业务层对象之间的依赖关系。 假设我有两个业务对象:
车轮服务
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?
只需像在构造函数中添加存储库依赖项一样添加它们:
public CarService(ICarRepository repository, IWheelService wheelservice)
{
...
}
您还可以
使用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 容器来解析所需的类。