温莎城堡:有没有一种方法可以在没有解决呼叫的情况下验证注册?

时间:2012-01-23 10:09:08

标签: c# castle-windsor

我目前对Castle Windsor注册的理解是,只能通过在根组件上调用Resolve来验证注册。但是,由于windsor的组件模型知道每个组件的依赖关系,因此应该可以测试是否可以满足所有依赖关系而无需实际实例化任何内容。想要这样做的主要原因是要进行注册的单元测试,这不需要我在启动时调用调用外部资源的组件。

例如。我有一个依赖于IChild的类Root:

public class Root : IRoot
{
    private IChild child;

    public Root(IChild child)
    {
        this.child = child;
    }
}

如果我将Root注册为IRoot,但不注册IChild。当我打电话给这样的决心时:

var container = new WindsorContainer().Register(
    Component.For<IRoot>().ImplementedBy<Root>()
    );

container.Resolve<IRoot>();

我收到错误:

MyNamespace.Root is waiting for the following dependencies: 

Services: 
- MyNamespace.IChild which was not registered. 

是否有类似的东西:

container.TestResolve<IRoot>();

那会走依赖图并检查是否可以满足所有依赖关系,但实际上并没有实例化任何依赖关系?

1 个答案:

答案 0 :(得分:28)

好的,有可能。感谢KrzysztofKoźmic向我展示了如何。不是很明显,但您可以使用Windsor的诊断子系统来引发注册的潜在问题。如果有任何配置错误的组件,我会整理一个静态方法:

private static void CheckForPotentiallyMisconfiguredComponents(IWindsorContainer container)
{
    var host = (IDiagnosticsHost)container.Kernel.GetSubSystem(SubSystemConstants.DiagnosticsKey);
    var diagnostics = host.GetDiagnostic<IPotentiallyMisconfiguredComponentsDiagnostic>();

    var handlers = diagnostics.Inspect();

    if (handlers.Any())
    {
        var message = new StringBuilder();
        var inspector = new DependencyInspector(message);

        foreach (IExposeDependencyInfo handler in handlers)
        {
            handler.ObtainDependencyDetails(inspector);
        }

        throw new MisconfiguredComponentException(message.ToString());
    }
}

你可以像这样使用它:

var container = new WindsorContainer().Register(
    Component.For<IRoot>().ImplementedBy<Root>()
    );

CheckForPotentiallyMisconfiguredComponents(container);

在这种情况下,我收到一条MisconfiguredComponentException并显示以下消息:

'WindsorSpikes.Root' is waiting for the following dependencies:
- Service 'WindsorSpikes.IChild' which was not registered.

WindsorSpikes.MisconfiguredComponentException:
'WindsorSpikes.Root' is waiting for the following dependencies:
- Service 'WindsorSpikes.IChild' which was not registered.

有关诊断子系统的更多详细信息,请参阅castle文档:

http://stw.castleproject.org/Default.aspx?Page=Debugger-views&NS=Windsor