How to: StructureMap and configuration based on runtime parameters?

Posted by user981375 on Stack Overflow See other posts from Stack Overflow or by user981375
Published on 2012-06-21T23:51:22Z Indexed on 2012/06/25 15:16 UTC
Read the original article Hit count: 164

In a nutshell - I want to be able to instantiate object based on runtime parameters. In this particular case there are only two parameters but the problem is that I'm facing different permutations of these parameters and it gets messy.

Here is the situation: I want to get an instance of an object specific to, say, given country and then, say, specific state/province. So, considering the US, there are 50 possible combinations. In reality it's less than that but that's the max. Think of it this way, I want to find out what's the penalty for smoking pot in a given country/state, I pass this information in and I get instantiated object telling me what it is.

To the code (for reference only):

interface IState
{
    string Penalty { get; }
}

interface ICountry
{
    IState State { get; set; }
    string Name { get; }
}

class BasePenalty : IState
{
    virtual public string Penalty { get { return "Slap on a wrist"; } }
}

class USA : ICountry
{
    public USA(IState state)
    {
        State = state;
    }

    public IState State { get; set; }
    public string Name { get { return "USA"; } }
}

class Florida: BasePenalty
{
    public override string Penalty { get { return "Public beheading"; } }
}

// and so on ... I defined other states
// which have penalties other than the "Slap on a wrist"

How do I configure my container that when given country and state combination it will return the penalty? I tried combinations of profile and contextual binding but that configuration was directly proportional to the number of classes I've created. I have already gone thru trouble of defining different combinations. I'd like to avoid having to do the same during container configuration. I want to inject State into the Country. Also, I'd like to return UsaBasePenalty value in case state is not specified. Is that possible? Perhaps these is something wrong with the design.

© Stack Overflow or respective owner

Related posts about configuration

Related posts about parameters