views:

374

answers:

2

Posted this on the structuremap group as well. We just started using structuremap last week, and are really digging it.


I'm sure I'm missing something simple.

I am trying to mimic the following code, using SM within my factory. I'm ok with having the container dependency in the factory class. The consensus in this thread seemed to be that this was the right approach: http://www.codeplex.com/unity/Thread/View.aspx?ThreadId=29697. If there is a better way, I'm open to hearing other ways of accomplishing this.

Basically my factory's Create method will take in an enum value (it might be an actual type, but either way it's not something controlled by the container), and should return the right instance. Note that the return types WILL be managed by SM. I don't want to put all the depenencies in the Ctor of the factory, since there could be many (!).

public class PreSaveActionFactory : IPreSaveActionFactory 
{ 
    public IPreSaveAction Create(MyEnumType enumType) 
    { 


        IPreSaveAction action; 


        switch (enumType) 
        { 
            case MyEnumType.Value1: 
                //imagine this has 3 Ctor arguments 
                action = new Value1PreSaveAction(); 
                break; 
            case MyEnumType.Value2: 
                //and imagine this has 4 completely different Ctor arguments 
                action = new Value2PreSaveAction(); 
                break; 


            default: 
                throw new NotSupportedException(); 
        } 


        return action; 
    } 
}

I link to the right section of the docs is fine, you don't need to write the code for me (although I won't complain :) ). I'd like to know what the factory looks like, and also the registry code.

Thanks,

Phil

+1  A: 

I've never tried it this way, but you can use the .WithName() method to provide an instance name, then presumably get the instance via ObjectFactory.GetNamedInstance().

Another approach (which I have used successfully) would be to create a dictionary of which acts as a typemapping. Look up the type there and then get an instance of that type via the ObjectFactory.

Wyatt Barnett
Using WithName() and GetNamedInstance() works! Took me a bit of time to understand, as I had not been thinking of the objects returned as existing instances, but more as on-demand instances. I've since done some debug tracing and reading, and have a little better understanding.Thanks for your help. Can't vote your answer up as I'm apparently too new to SO.
Phil Sandler
A: 

As for the registration, I'm thinking you'll want to use Conditional Object Construction.

Chris Missal