Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace factory pattern with dependency injection

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();
        }
    }
}
like image 887
Anca Avatar asked Apr 30 '26 17:04

Anca


2 Answers

Yes it can be refactored - inject the service into SendIncident, or its class.

like image 160
Joe Ratzer Avatar answered May 03 '26 06:05

Joe Ratzer


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:

  • Use a Metadata Role Hint
  • Use a Role Interface Role Hint
  • Use a Partial Type Name Role Hint

My personal preference is the Partial Type Name Role Hint.

like image 20
Mark Seemann Avatar answered May 03 '26 07:05

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!