How do I tell StructureMap 3 to use a specific constructor for a specific type?
I am using StructureMap (version 3.1.4.143) for general dependency resolution in my web API project and so far it works fine. I want structmap to implement it by default when you have chosen a constructor with most parameters. However, for a specific type, I want to use a specific constructor to be used.
eg. I have a 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 a parameterless constructor. How do I do this in StructureMap 3? (I could do this for all types by instantiating IConstructorSelector and applying it as a policy like below)
x.Policies.ConstructorSelector<ParamLessConstructorSelector>();
source to share
Answering my own question:
This is the correct way to do it in StructureMap 3. With SelectConstructor, the structure structure displays the constructor from the given expression.
x.ForConcreteType<Service>().Configure.SelectConstructor(() => new Service());
Or, it can be specified by using to use.
x.For<IService>().Use<Service>().SelectConstructor(() => new Service());
Check out the documentation at the Github StructureMap docs .
If this rule needs to be applied throughout the application, this rule can be applied as a policy by instantiating IConstructorSelector
public class ParamLessConstructorSelector : IConstructorSelector
{
public ConstructorInfo Find(Type pluggedType)
{
return pluggedType.GetConstructors().First(x => x.GetParameters().Count() == 0);
}
}
and container configuration.
x.Policies.ConstructorSelector<ParamLessConstructorSelector>();
source to share
You can specify which constructor to use for a specific type. Somewhere near:
x.SelectConstructor<Service>(() => new Service());
For more information, see. In documentation .
Edit:
For StructureMap3, this would be:
x.Policies.ConstructorSelector(...)
source to share