Windsor Container:在Code vs Xml中注册内容

时间:2008-09-18 14:34:47

标签: .net inversion-of-control castle-windsor

从我读到的关于Windsor / Microkernel的内容来看,理论上可以使用带代码的xml文件来完成所有操作。事实上 - 如果我错了,请纠正我 - 似乎Windsor层的主要贡献是为Microkernel已经可以做的事情添加xml配置。

然而,我最近一直在努力寻找如何在代码中实现一些稍微复杂的功能(即how to assign a default constructor argument value)。现在,当我要在我的生产版本中使用xml时,我正在为我的测试注册代码中的组件,这就变得非常棘手。不幸的是他们的文档状态以及我能找到的唯一文章专注于xml注册这一事实并没有帮助。

有没有人知道一个列出如何在代码中注册事物的来源(最好用xml等价物)?除了存在之外,是否有人只是知道一个开源/示例项目,其中有很多非xml使用Castle Windsor / Microkernel?

1 个答案:

答案 0 :(得分:6)

我总是发现单元测试是学习如何使用开源项目的最佳方式。 Castle具有流畅的界面,允许您在代码中执行所有操作。来自WindsorDotNet2Tests测试用例:

[Test]
    public void ParentResolverIntercetorShouldNotAffectGenericComponentInterceptor()
    {
        WindsorContainer container = new WindsorContainer();
        container.AddComponent<MyInterceptor>();

        container.Register(
            Component.For<ISpecification>()
                .ImplementedBy<MySpecification>()
                .Interceptors(new InterceptorReference(typeof(MyInterceptor)))
                .Anywhere
            );
        container.AddComponent("repos", typeof(IRepository<>), typeof(TransientRepository<>));

        ISpecification specification = container.Resolve<ISpecification>();
        bool isProxy = specification.Repository.GetType().FullName.Contains("Proxy");
        Assert.IsFalse(isProxy);
    }

如需了解更多信息,请查看ComponentRegistrationTestCaseAllTypesTestCase

还有一个用于执行此操作的DSL,这是我的首选选项,因为它真正简化了事物并提供了很多易于扩展的功能。 DSL被称为Binsor,你可以在这里阅读更多信息:http://www.ayende.com/Blog/archive/7268.aspx但同样,infor的最佳位置是单元测试。这是binsor可能的代码示例:

for type in AllTypesBased of IController("Company.Web.Controller"):
    component type

这两行将注册将IController接口继承到容器中的类型:D

相关问题