Please see the code below, which I took from Jimmy Bogards Wicked domain models:
public class OfferAssignmentService
{
private readonly IMemberRepository _memberRepository;
private readonly IOfferTypeRepository _offerTypeRepository;
private readonly IOfferValueCalculator _offerValueCalculator;
private readonly IOfferRepository _offerRepository;
public OfferAssignmentService(
IMemberRepository memberRepository,
IOfferTypeRepository offerTypeRepository,
IOfferValueCalculator offerValueCalculator,
IOfferRepository offerRepository
)
{
_memberRepository = memberRepository;
_offerTypeRepository = offerTypeRepository;
_offerValueCalculator = offerValueCalculator;
_offerRepository = offerRepository;
}
public void AssignOffer(Guid memberId, Guid offerTypeId)
{
// Retreive
var member = _memberRepository.GetById(memberId);
var offerType = _offerTypeRepository.GetById(offerTypeId);
// Delegate to business objects
var offer = member.AssignOffer(offerType, _offerValueCalculator);
// Save
_offerRepository.Save(offer);
}
}
Why are the repositories injected into the service? Say I have an app, which has four clients (mobile; WPF; MVC4; Win Forms), then all these clients have to create instances of these repositories and pass them to the service. Why does the service not just create them i.e. in one place.
I am obviously missing something here.
Update
If I create the repositories in the Serivce layer then their are four dependencies i.e. one for _memberRepository; one for _offerTypeRepository; one for _offerValueCalculator and one for _offerRepository. If I create all these instances in the four clients then I am creating 16 dependencies i.e. 4*4. I realise I am missing something fundamental here.