温莎容器:在Code vs Xml中注册内容

时间:2020-03-06 14:21:38  来源:igfitidea点击:

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

但是,最近我一直在努力寻找如何在代码中实现一些稍微复杂的功能(即,如何分配默认的构造函数参数值)。现在,当我要在生产版本中使用xml时,我正在代码中注册组件以进行测试,这变得非常成问题。他们文档的不幸状态以及我能找到的唯一文章都集中在xml注册这一事实并没有帮助。

有谁知道列出如何在代码中注册内容的资源(最好使用xml等效项)?除此以外,没有人会简单地知道一个开放源代码/示例项目,其中Castle Windsor / Microkernel大量使用了非XML?

解决方案

我总是发现看单元测试是学习如何使用开源项目的最佳方法。 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);
    }

有关更多信息,请查看ComponentRegistrationTestCase和AllTypesTestCase

还有一个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