How to use dependency injection for external dependencies?

I think I almost figured it out.

Let's say I want my application to send SMS messages. But I'm not sure if I should go with Twilio or SomeOtherSMSService. In fact, I do not care. So I have something simple, so I could continue to develop my application.

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

Now I want to try Twilio. I'm embarrassed here. I can install it as a Nuget package, but I don’t think that their C # shell using their REST API will completely match my interface .. and modifying does not seem like a good idea.

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

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

And the best thing I have to do is WRAP in my own interface implementation. Something like that.

 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 adheres to the principle of dependency on injection with this, but it seems to me that I need to create an instance of TwilioRestClient in the default constructor, which is exactly what I would like to use for dependency injection: s.

Is this approach right? If not, how would you do it?

Please, help.

+4
source share
2 answers

This is perfectly acceptable. You abstract the dependence of TwilioRestClient on the consumption class. Thus, you can toss FakeSMSService in your controllers for unit testing. You do not need unit test Twilio.

+7
source

The twillio blog has a good entry, we don’t use mvc controllers for our project, so we can’t use it, but we will share the link if it helps you.

https://www.twilio.com/blog/2012/11/adding-dependency-injection-to-your-asp-net-mvc-twilio-app-using-mef.html

The article was a little over my head, but it looks useful.

0
source

All Articles