Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use dependency injection for external dependencies?

I think I almost got this.

Say I want my app to send SMSs. But Im not sure yet if I should go with Twilio or SomeOtherSMSService. In fact, I dont really care yet. So I have something as simple as this so I could keep developing my app.

public interface ISMSService{
    public bool SendMessage(string to, string message);
}

now I want to try Twilio. This is where I get confused. I can install it as a Nuget package but I dont think their C# wrapper that uses their REST API is going to match my interface at all.. and modifying it doesnt seem a good idea either.

from the readme I can see that to use it I need to do something like this

var msg = twilio.SendSmsMessage("+15551112222", "+15553334444", "Can you believe it's this easy to send an SMS?!");

And my best guess is that I should WRAP this into my own implementation of the interface. Something like this.

using Twilio;

public TwilioSMSService : ISMSService
{
    TwilioRestClient twilio;
    public TwilioSMSService()
    {
        twilio = new TwilioRestClient("accountSid", "authToken");

    }

    public bool SendMessage(string to, string message)
    {
        var msg = twilio.SendSmsMessage("+15551112222", to, message);
        if (msg != null) return true;
        return false;
        // this would obviously need more logic.
    }

I want to make sure that Im keeping dependency injection principle with this but it seems fishy to me that I need to instantiate TwilioRestClient in the default constructor which is exactly what dependency injection i supposed to help you avoid :s .

Is this approach correct? If not how would you do it?

Please Help.

like image 219
nacho10f Avatar asked Sep 22 '11 15:09

nacho10f


1 Answers

That's perfectly acceptable. You are abstracting the dependency of TwilioRestClient away from the consuming class. That way you can in your controllers toss in a FakeSMSService for unit testing. You shouldn't need to unit test Twilio.

like image 88
Daniel A. White Avatar answered Sep 30 '22 06:09

Daniel A. White