Tom
Tom

Reputation: 16246

MVC DI Castle Typed Factory Facility with parameters

I am playing with typed factory implementation, and I've been reading the castle pages about typed factory. I would like to know how to pass construction parameters into the generic typed factory.

public interface IFacilityFactory {
  IFacility<T> Create<T>(); // how to pass some parameter(s) to any T constructor?
}

Could you please give me some direction? Thank you very much.

Upvotes: 0

Views: 332

Answers (1)

Phil Degenhardt
Phil Degenhardt

Reputation: 7264

It doesn't make much sense since you would need to provide a common set of constructor parameters for an unbounded set of possible types that could be used as the generic type parameter 'T'.

However, putting sense aside, I believe you could do it. You simply declare the parameters on the factory interface that you want passed through on the Resolve() Windsor will perform when you use the factory. The parameter names will become dictionary keys. You don't need to declare constructor properties that will be resolved from the container itself.

E.g. say we have a component Bar registered in the container and dependent class Foo:

public class Foo
{
    // Constructor requires Bar to be resolved from the container
    public Foo(int something, Bar bar, string somethingElse)
    {
       ...
    }
}

We would declare factory interface:

public interface IGenericFactory
{
    T Create<T>(int something, string somethingElse)
}

When we use the typed factory, Windsor will pass through the two parameters and resolve the other parameter (bar) from the container. The 'something' and 'somethingElse' parameters simply get pushed into a Dictionary and Windsor figures out if it can use them or not. Of course it will be able to use them if you call Create<Foo>(1, "") but they would probably be redundant for any type other than Foo.

Upvotes: 2

Related Questions