Unity 设计的好坏:注入完整的容器还是仅注入显式接口?

Good or bad Unity design: Injecting the complete container or only explicit Interfaces?

这是一个糟糕或好的设计问题。

我发现总是在我的模块中注入完整的 Unity 容器非常方便。

1.) 你永远不知道你需要什么资源。 2.) 如果您需要容器的更多资源,class 构造函数永远不需要更改。

看起来像这样:

public class ServiceLocator: IServiceLocator
{
    private IUnityContainer _container = null;

    public ServiceLocator(IUnityContainer container)
    {
        _container = container;
    }


    public void DoSomething()
    {
       var x = this._container.Resolve<IXInterface>();
       var y = this._container.Resolve<IYInterface>();      
       x.Do();
       y.Do();
   }
}

在教程和统一示例中,我经常看到,您只应注入真正需要的资源。看起来像这样:

public class ServiceLocator: IServiceLocator
{
    private XInterface _x = null;
    private YInterface _y = null;

        public ServiceLocator(Ixnterface x,  IYnterface y)
        {
            _x = x;
            _y = y;
        }


         public void DoSomething()
        {
            _x.Do();
            _y.Do();    
        }
}

我的问题是:

您认为什么是更好的设计?

当 Unity 容器中包含所有资源时,为什么只注入显式接口?

以后有什么问题?

我看到的未来唯一的问题是,你在未来总是必须有一个 Unity 容器,如果你没有,你必须重写模块。

你怎么看?

编辑: 我找到的一些最佳答案是,第一个版本不是依赖注入,它是某种 "Service Locator Pattern",这可能导致很多问题。

可以在这里找到:

http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/

在第一种方法中,您依赖于您需要的接口,而且您向容器添加另一个接口:

var x = this._container.Resolve<IXInterface>();
var y = this._container.Resolve<IYInterface>();  

所以你首先违背了 DI 的主要原因之一。