I am trying to use a method on a generic factory class in my structuremap registry. Normally, i would use the following when registering a type using a factory method:
For<Foo>().Use(x => new FooFactory().GetFoo());
And the following when registering a generic type:
For(typeof(ISomeGeneric<>)).Use(typeof(SomeGeneric<>));
How can I combine the two and retrieve a generic type from a generic factory method? I think it should be something like:
For(typeof(IFoo<>)).Use(typeof(x => new FooFactory<>().Create(someParameter));
This just gives a
"Cannot convert lambda expression to type object because it is not a delegate type"
error. I've tried various combinations but am stumped. Any ideas?
Thanks.
This is possible, BUT I would look for an alternative if you can. The issue is that to work with the open generic, you have to use some reflection. This means you will take a performance hit.
What you are doing in order is the following:
StructureMap takes care of casting the output to the right interface.
Better Solution
Instead of using the IFoo directly, use the IFooFactory. This makes it much cleaner, you have an open generic mapping to the IFooFactory<>. Then just get the type of FooFactory you need to generate your objects.