Reputation: 1507
I am using StructureMap in my small project. I have a class which needs to be constructed using instances of classes which can easily be delivered by StructureMap (Bar
), but the constructor patameters include some arguments which are not know beforehand.
class Bar { }
class Foo
{
public Foo(string magic, Bar bar) { }
}
So in my code somewhere I need to get an instance of Foo
. In this piece of code I know the desired value of magic
.
How should I create my Foos?
What I am doing now is I usually create a factory, inject IContainer
and make a CreateFoo
method accepting the stuff known at runtime.
class FooFactory
{
private readonly IContainer _container;
public FooFactory(IContainer container)
{
_container = container;
}
public Foo CreateFoo(string magic)
{
return _container.With("magic").EqualTo(magic).GetInstance<Foo>();
}
}
I inject FooFactory
wherever I need to have a new Foo
created and my classes do not need to know how exactly is Foo
made.
I know I could inject IContext and create the Foos without the factory, but it seems smelly when the construction code gets more complicated and needs to be copied.
Are the any other alternatives besides the factory?
Upvotes: 1
Views: 1007
Reputation: 361
Try the SM docs for explicit arguments: http://structuremap.github.io/resolving/passing-arguments-at-runtime/
Upvotes: 1