标签: compositionroot

组合根是否需要单元测试?

我试图找到答案,但似乎没有直接讨论过很多.我有一个我的应用程序的组合根,我创建一个DI容器并在那里注册所有内容,然后解决所有依赖项所需的顶级类.由于这一切都在内部发生 - 因此很难对组合根进行单元测试.你可以做虚拟方法,受保护的字段等等,但我不是为了能够进行单元测试而引入这些东西的忠实粉丝.其他类没有大问题,因为它们都使用构造函数注入.所以问题是 - 根本测试组合根是否有意义?它确实有一些额外的逻辑,但并不多,在大多数情况下,在应用程序启动期间会弹出任何故障.我有一些代码:

public void Initialize(/*Some configuration parameters here*/)
    {
        m_Container = new UnityContainer();

        /*Regestering dependencies*/

        m_Distributor = m_Container.Resolve<ISimpleFeedMessageDistributor>();
    }

    public void Start()
    {
        if (m_Distributor == null)
        {
            throw new ApplicationException("Initialize should be called before start");
        }

        m_Distributor.Start();
    }

    public void Close()
    {
        if (m_Distributor != null)
        {
            m_Distributor.Close();
        }
    }
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection compositionroot

9
推荐指数
1
解决办法
958
查看次数

组合根与服务定位器

我一直在阅读这两种解决依赖关系的方法,并找到了一些 ninject 实现的示例代码。

对于服务定位器遵循类似

 public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
 {
    IKernel kernel;

    public NinjectDependencyResolver(IKernel kernel)
        : base(kernel)
    {
        this.kernel = kernel;
    }

    public IDependencyScope BeginScope()
    {
        return new NinjectDependencyScope(kernel.BeginBlock());
    }
}
Run Code Online (Sandbox Code Playgroud)

public class NinjectDependencyScope : IDependencyScope
{
    IResolutionRoot resolver;

    public NinjectDependencyScope(IResolutionRoot resolver)
    {
        this.resolver = resolver;
    }

    public object GetService(Type serviceType)
    {
        if (resolver == null)
            throw new ObjectDisposedException("this", "This scope has been disposed");

        return resolver.TryGet(serviceType);
    }

    public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
    {
        if (resolver == null)
            throw new …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection ninject inversion-of-control compositionroot

1
推荐指数
1
解决办法
1241
查看次数