我可以在没有接口的情况下使用IoC容器吗?

时间:2018-03-20 13:05:59

标签: asp.net-web-api asp.net-web-api2 inversion-of-control ninject ioc-container

我的应用程序可能包含80多个Web-Api控制器。每个控制器都有以下构造函数定义:

public class AlertsController : ApiController
{         
     IAlertsService _alertsService;
     public AlertsController(IAlertsService alertsService)
     {
         _alertsService = alertsService;
     }
}

所以每次我必须为了使用IoC而定义一个新接口,仅此而已。问题是我没有发现有这么多的接口只是为了避免耦合层。是否存在继续使用IoC的解决方案,但在我的情况下,没有必要定义如此多的接口?

提前致谢,

1 个答案:

答案 0 :(得分:0)

OP未指定IAlertsService 的用途,但是在Dependency Inversion Principle之后,客户端应定义他们需要的API,然后由具体决定类以实现所需的API。

为了便于讨论,我们假设IAlertsService看起来像这样:

public interface IAlertsService
{
    void Foo(Bar bar);
    Baz Qux();
}

无需定义任何接口,您可以改为注入两个委托,如下所示:

public class AlertsController : ApiController
{         
     private readonly Action<Bar> foo;
     private readonly Func<Baz> qux;

     public AlertsController(Action<Bar> foo, Func<Baz> qux)
     {
         this.foo = foo;
         this.qux = qux;
     }
}

如果一个类只需要foo功能,就不需要注入qux,反之亦然。

由于基类库已经定义了泛型ActionFunc委托,因此您不必为依赖项声明任何新类型。

一旦习惯了这种编程风格,您可能会意识到自己只是在做ad-hoc, impure, 'functional' programming,在这种情况下,最好使用F#进行编程。

相关问题