Search code examples
.netinversion-of-controlstructuremapstructuremap3

How to tell StructureMap 3 to use specific constructor for specific type?


I am using StructureMap (version 3.1.4.143) for general dependency resolution in my Web API project, and it's working fine so far. I want structuremap to follow it's default behavior of selecting the constructor with most parameters. However, for a specific type I want to use a specific constructor to be used.

e.g. I have some service contract

public interface IService 
{
    void DoSomething();
}

and implementation like

public class Service : IService 
{
    public Service() { //something }
    public Service(IRepo repo, ILogger logger) { //something }
    //rest of the logic
}

For this type only, I want to use the parameter-less constructor. How do I do that in StructureMap 3 ? (I could do that to all types by creating an instance of IConstructorSelector and applying that as policy like below)

x.Policies.ConstructorSelector<ParamLessConstructorSelector>();

Solution

  • Answering my own question:

    This is the right way to do that in StructureMap 3. With SelectConstructor, structuremap infers the constructor from the given expression.

    x.ForConcreteType<Service>().Configure.SelectConstructor(() => new Service());
    

    Or, it can be specified with For-Use-mapping.

    x.For<IService>().Use<Service>().SelectConstructor(() => new Service());
    

    Check the documentation in Github StructureMap docs.

    If this rule needs to applied throughout the application, the rule can be applied as a policy by creating an instance of IConstructorSelector

    public class ParamLessConstructorSelector : IConstructorSelector
    {
        public ConstructorInfo Find(Type pluggedType)
        {
            return pluggedType.GetConstructors().First(x => x.GetParameters().Count() == 0);
        }
    }
    

    and configuring the container.

    x.Policies.ConstructorSelector<ParamLessConstructorSelector>();