Castle Windsor UsingFactory xml 备选方案

Castle Windsor UsingFactory xml alternative

我有一个普通的温莎城堡组件注册命令:

container.Register(Component.For<IEntity>()
                            .UsingFactoryMethod(() => new EntityFactory().CreateEntity()));

我需要 XML 配置选项来扩展我的 UCommerce。 我已尝试注册它 as described here 但由于异常而无法使用:

Could not convert string 'Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Facilities.FactorySupport' to a type. Assembly was not found. Make sure it was deployed and the name was not mistyped.`

有人遇到过同样的挑战吗?

请注意链接文章顶部的免责声明:

Prefer UsingFactoryMethod over this facility: while the facility provides programmatic API it is deprecated and its usage is discouraged and won't be discussed here. Recommended approach is to use UsingFactoryMethod method of fluent registration API to create components. This limits the usefulness of the facility to XML-driven and legacy scenarios.

如果您仍然想使用 XML(确保您有充分的理由),那么您需要执行两个步骤:

  1. 修复异常。它说找不到名为"Castle.Facilities.FactorySupport"的程序集。这是一个独立于 Castle Windsor 分发的库,您可以 get it from NuGet。如果您确实安装了它,请确认您正在部署该程序集。

  2. 创建工厂对象。该工具不支持使用任意方法;你必须给它一个类型并将它指向要使用的方法。因此,您将创建这样的类型:

    public class EntityFactory
    {
        public IEntity Create()
        {
            return new EntityFactory().CreateEntity();
        }
    }
    

    那么您的 XML 配置将如下所示:

    <components>
       <component id="entityfactory"
                  type="Your.Namespace.EntityFactory, Your.AssemblyName"/>
       <component id="entity"
                  type="Your.Namespace.IEntity, Your.AssemblyName"
                  factoryId="entityfactory" 
                  factoryCreate="Create" />
    </components>