Telling StructureMap to use another Constructor

后端 未结 3 1234
忘了有多久
忘了有多久 2021-01-04 21:12

I have a class with 2 constructors.

MyClass()

and

MyClass(IMyService service)

How do I tell StructureMap then whenever I do a \'new MyClass()

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 21:38

    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(), 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(() => 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().Use(ctx => new MyClass(ctx.GetInstance()))
    

提交回复
热议问题