1
votes

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?

1
Change your design. Your application componens should not require runtime data during construction.Steven
I like this. It will add some "providers" and "contexts" to my otherwise simple application though... Is it ok to create an initialization method accepting my object's settings? I'm making a small game and need stuff like spawn posistion, initial object speed, etc.user1713059

1 Answers