Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap: Concrete class constructor accepts multiple arguments of same interface type

I want to use StructureMap ObjectFactory to handle the instantiation of my classes used by my WCF service. While my limited experience is sufficient to handle the simple 1:1 mappings between one interface and that one, single class that implements it, I've hit a snag where a constructor accepts multiple parameters of the same interface.

I reckon I can associate multiple concrete classes to the same interface by giving each mapping a name, but how do I tell StructureMap what mapping to use for the first and the second constructor parameter?

This is the class I want ObjectFactory to handle for me:

public class MasterPolicy {
    public MasterPolicy(IPolicy alfaPolicy, IPolicy numericPolicy)
    {
        AlphaPolicy = alphaPolicy;
        NumericPolicy = numericPolicy;
    }

    public IPolicy AlphaPolicy {get; private set; }
    public IPolicy NumericPolicy {get; private set; }

    public bool IsValid(string s)
    {
         if (!AlphaPolicy.IsValid(s)) return false;
         if (!NumericPolicy.IsValid(s)) return false;
         return true;
    }
}

The IPolicy interface is implemented by more than one class:

public interface IPolicy
{
    bool IsValid(string s);
}

public class AlphaPolicy : IPolicy
{
    public bool IsValid(string s) { return true; }
}

public class NumericPolicy : IPolicy
{
    public bool IsValid(string s) { return true; }
}

(Of course, MasterPolicy could too implement the IPolicy interface).

like image 970
Sigurd Garshol Avatar asked Dec 16 '22 07:12

Sigurd Garshol


1 Answers

You can specify constructor dependencies and tell structure map which named argument should have which dependency:

For<MasterPolicy>.Use<MasterPolicy>()
    .Ctor<IPolicy>("alphaPolicy").Is<AlphaPolicy>()
    .Ctor<IPolicy>("numericPolicy").Is<NumericPolicy>();
like image 141
PHeiberg Avatar answered Feb 23 '23 00:02

PHeiberg