Search code examples
c#castle-windsor

Using Castle Typed Factory Facility to get specific implementation


I am building a WPF application that relies on being able to instantiate various forms at runtime, so I am trying to have Castle give me a factory implementation with this ability and all of the forms that I want to be able to create in this manner implement the IBaseForm interface.

Here is what my factory interface currently looks like:

public interface IFormFactory
{
    IBaseForm Create(Type formType, string header);
    void Release(IBaseForm component);
}

Where the formType parameter is what I want castle to use for its lookup which ofcourse doesn't work, in this scenario Castle will always use the return type of create for the lookup.

So is there any convention that the type factory facility allows for that would support this behavior, or is there another way that I can implement this factory while maintaining abstraction from the container?


Solution

  • I was able to solve this problem by adding a custom TypedFactoryComponentSelector along with my factory. Here is the implementation:

    public class FormFactoryComponentSelector : DefaultTypedFactoryComponentSelector
    {
        protected override Type GetComponentType(MethodInfo method, object[] arguments)
        {
            if (arguments.Length >= 1 && arguments[0] is Type)
            {
                return (Type)arguments[0];
            }
            return base.GetComponentType(method, arguments);
        }
    }