Reputation: 174
Apologies if this has been asked before, I can't find a similar question so I can only assume my terminology is wrong!
Anyway I'm wondering how to handle dependencies between business layer objects. Say I have two business objects:
A Wheel Service
public class WheelService : IWheelService
{
private IWheelRepository Repository { get; set; }
public WheelService(IWheelRepository repository)
{
this.Repository = repository;
}
public Wheel Get(int id) { ... }
}
And a Car Service
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
}
}
What sort of architecture would you use that would all me to call methods of one business object from another in a loosely coupled way that would also fit well with TDD?
Upvotes: 0
Views: 110
Reputation: 35925
You can also use a Builder
pattern, which will be useful if you have many dependencies
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, ...);
}
}
Here is the usage
ICarService carService = new CarService();
IWheelService wheelService = new WheelService();
...
carService.WithWheelService(wheelService)
.WithSomethingElse(somethingElse)
.WithLights(brightLights)
.UsingMainColour(selectedColour);
var car = carService.Build()
See these lines
ICarService carService = new CarService();
IWheelService wheelService = new WheelService();
This is where you can use IoC container to resolve the needed classes.
Upvotes: 0
Reputation: 27944
Just add them the same way you add your repository dependence in your constructor:
public CarService(ICarRepository repository, IWheelService wheelservice)
{
...
}
Upvotes: 2