Telling StructureMap to use another Constructor
Asked Answered
A

3

10

I have a class with 2 constructors.

MyClass()

and

MyClass(IMyService service)

How do I tell StructureMap then whenever I do a 'new MyClass()' it should actually call the second constructor and not the first constructor.

Please help.

Abirritate answered 9/8, 2011 at 15:3 Comment(0)
W
23

If you call new MyClass(), then StructureMap is not involved at all. No amount of StructureMap configuration will change the behavior.

If you call ObjectFactory.GetInstance<MyClass>(), StructureMap will by default call the constructor with more parameters.

If you want StructureMap to use a different constructor, you can specify the constructor (via PHeiberg's answer):

x.SelectConstructor<IMyClass>(() => new MyClass(null));

Or you can just tell StructureMap explicitly how to create the instance using the overload of Use() that accepts a Func<>:

x.For<IMyClass>().Use(ctx => new MyClass(ctx.GetInstance<IMyService>()))
What answered 9/8, 2011 at 16:50 Comment(1)
What if I want it to use a MyClass constructor that has 2 parameters? ctx.GetInstance<> only permits 1 type parameter.Vikkivikky
M
6

Joshua's answer is covering all aspects. As a side note in order to configure Structuremap to choose a specific constructor without hardcoding the arguments to the constructor as done in Joshua's example you can use the SelectContructor method:

x.SelectConstructor<MyService>(() => new MyService());

The lambda in the SelectConstructor method call should invoke the needed constructor (put nulls or any value of the correct type for all parameters present). See the documentation for further info.

Millican answered 10/8, 2011 at 8:1 Comment(0)
E
0

When using a DI container like structuremap it's best to have just a single constructor on every class. This constructor has to resolve all the dependencies of the class, if IMyService is a dependency (which looks a bit strange though) this should always be resolved when instantiating so the parameterless constructor is not needed.

Elyssa answered 11/8, 2011 at 6:0 Comment(1)
Sorry, I have corrected now. Instead of CMyService, I have user CMyClass. Thanks.Abirritate

© 2022 - 2024 — McMap. All rights reserved.