Search code examples
dependency-injectionconfigurationcastle-windsorumbraco-ucommerce

Castle Windsor UsingFactory xml alternative


I have an ordinary Castle Windsor component registration command:

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

I need the XML configuration alternative in order to extend my UCommerce. I've tried to register it as described here but it doesn't work due to exception:

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.`

Have anyone faced equal challenge?


Solution

  • Note the disclaimer at the top of your linked article:

    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.

    If you still want to use XML (make sure you have a really good reason), then there are two steps you need to take:

    1. Fix the exception. It says it cannot find the assembly named "Castle.Facilities.FactorySupport". This is a library that is distributed separately from Castle Windsor, and you can get it from NuGet. If you do have it installed, confirm that you are deploying that assembly.

    2. Create a factory object. The facility doen't support using an arbitrary method; you must give it a type and point it to the method to use. So, you'd create a type like this:

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

      Then your XML configuration would look something like this:

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