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).
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With