从基类开始的参数化构造函数难题?

时间:2018-08-03 11:23:35

标签: c# oop asp.net-web-api constructor

在Web api设置中,调用了参数化的构造函数AssignmentController(ProfileConfigCAWP pc)。我要停止这个。

  

我不是要调用参数化.ctor之一。两种Web API都不   pipleline会做,因为IMHO Web API管道会实例化   无参数的.ctor,(除非注入视力,   就我而言,我没有在任何地方传递ProfileConfigCAWP   现在。

public class BaseApiController : ApiController
{
    //1st call
    public BaseApiController()
    {

    }
}

//Web Api Controller
public class AssignmentController : BaseApiController
{

    public AssignmentController()
    {

    }

    //2nd call
    public AssignmentController(ProfileConfigCAWP pc)
    {
        //Why does this gets invoked, I'm worried Unity Container depency injection, is playing around
        if (pc != null && pc.LoggedinAccountId != Guid.Empty)
        {
            CAWPConfigure(pc);
        }
    }
}

即使我尝试了tweaking with base keyword,以便基础程序也可以明确知道要回调的构造函数。

public class BaseApiController : ApiController
{
    //1st call
    public BaseApiController()
    {

    }
}

//Web Api Controller
public class AssignmentController : BaseApiController
{

    public AssignmentController() : base()
    {

    }

    //2nd call
    public AssignmentController(ProfileConfigCAWP pc) : this()
    {
        //Why does this gets invoked, I'm worried Unity Container depency injection, is playing around
        if (pc != null && pc.LoggedinAccountId != Guid.Empty)
        {
            CAWPConfigure(pc);
        }
    }
}

编辑: 我不是试图调用参数化的.ctor之一。这两个Web API都不会做,因为IMHO Web API管道将实例化无参数.ctor,(除非出现注入视力,在我的情况下,我现在没有在任何地方传递ProfileConfigCAWP

1 个答案:

答案 0 :(得分:2)

默认情况下,Unity选择具有最大参数数量的构造函数。

要覆盖此行为,您可以使用InjectionConstructorAttribute装饰所需的构造函数。

public class AssignmentController : BaseApiController
{
    [InjectionConstructor]
    public AssignmentController() : base()
    {
    }
}

一种不那么麻烦的选择是更改注册。

container.RegisterType<AssignmentController>(new InjectionConstructor());