remi bourgarel
remi bourgarel

Reputation: 9389

How to choose between constructor / parameter injection?

My question is a bit vague ...

Let's say I have this process for sending a mail to a Shop when there is a new order

class BookingMessager : IBookingMessager{
  BookingMessager(IBookingDataSource source,IBookingMessageFactory messageFactory,IMessager messager){
    this.source = source;
    this.messageFactory= messageFactory;
    this.messager = messager;
  }
  void SendBookingMessage(int idBooking){
    Booking aBooking = source.GetById(idBooking);
    BookingMessage aMessage = messageFactory.Create(aBooking);
    messager.SendMessage(aBooking.Shop.Contact,aMessage.Title,aMessage.Content);
  }
}

This is working well.

New requirement : I have to change my message body depending on the Shop.

I though about these solutions : I create a IBookingMessageFactory that'll call the required IBookingMessageFactory depending on the shop like that

BookingMessage Create(Booking aBooking){
return this.BookingMessageFactoryIndex.ContainsKey(aBooking.Shop.ID) ? this.BookingMessageFactoryIndex[aBooking.Shop.ID].Create(aBooking) : this.default.Create(aBooking);
}

Or I inject the IBookingMessageFactory as a parameter, but that'll force me to update my interface IBookingMessager :(

What is the best solution ? Is my first code OK ? How do I choose between constructor and parameter injection ?

Upvotes: 1

Views: 103

Answers (1)

Steven
Steven

Reputation: 172835

Letting the IBookingMessageFactory return a shop-specific BookingMessage looks fine by me. It seems you are using a composite/decorator IBookingMessageFactory that will delegate to a shop-specific implementation, which is great, since this keeps things simple.

Upvotes: 1

Related Questions