如何对外部依赖项使用依赖项注入?

nac*_*10f 4 asp.net asp.net-mvc dependencies dependency-injection

我想我几乎得到了这个.

说我希望我的应用程序发送短信.但我还不确定我是否应该使用Twilio或SomeOtherSMSService.事实上,我真的不在乎.所以我有一些简单的东西,所以我可以继续开发我的应用程序.

public interface ISMSService{
    public bool SendMessage(string to, string message);
}
Run Code Online (Sandbox Code Playgroud)

现在我想试试Twilio.这是我感到困惑的地方.我可以将它安装为Nuget包但我不认为他们使用REST API的C#包装器将完全匹配我的界面..并且修改它似乎也不是一个好主意.

从自述文件我可以看到使用它我需要做这样的事情

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

我最好的猜测是我应该把它作为我自己的接口实现.像这样的东西.

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.
    }
Run Code Online (Sandbox Code Playgroud)

我想确保我保持依赖注入原则,但我觉得我需要在默认构造函数中实例化TwilioRestClient,这正是我应该帮助你避免的依赖注入:s.

这种方法是否正确?如果不是,你会怎么做?

请帮忙.

Dan*_*ite 7

那是完全可以接受的.您正在抽象TwilioRestClient远离消费类的依赖性.这样你就可以在你的控制器中FakeSMSService进行单元测试.你不应该对Twilio进行单元测试.