I have the following situation: a collection of objects have to be sent to different third parties based on a specific property of each object (the property is defined as an Enum). I intend to implement this using the Factory pattern like below.
Can this be refactored to use dependency injection instead?
public class ServiceA: IThirdParty
{
public void Send(Ticket objectToBeSent)
{
// a call to the third party is made to send the ticket
}
}
public class ServiceB: IThirdParty
{
public void Send(Ticket objectToBeSent)
{
// a call to the third party is made to send the ticket
}
}
public interface IThirdParty
{
void Send(Ticket objectToBeSent);
}
public static class ThirdPartyFactory
{
public static void SendIncident(Ticket objectToBeSent)
{
IThirdParty thirdPartyService = GetThirdPartyService(objectToBeSent.ThirdPartyId);
thirdPartyService.Send(objectToBeSent);
}
private static IThirdParty GetThirdPartyService(ThirdParty thirdParty)
{
switch (thirdParty)
{
case ThirdParty.AAA:
return new ServiceA();
default:
return new ServiceB();
}
}
}
Yes it can be refactored - inject the service into SendIncident, or its class.
As far as I can tell, this question is about run-time selection or mapping of one of several candidate Strategies - in this case selecting the correct IThirdParty implementation based on a ThirdParty enum value.
There are at least three ways to do this in, and none of them require a factory:
My personal preference is the Partial Type Name Role Hint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With