简体   繁体   English

为什么不执行BaseController的重载构造函数?

[英]Why is BaseController's overloaded constructor not being executed?

I have a base controller which is defined as follows, but the constructor that takes the ISiteService never gets executed: 我有一个定义如下的基本控制器,但是使用ISiteService的构造ISiteService永远不会执行:

public class BaseController : Controller
{
    private ISiteService _siteService;

    public BaseController() {}

    public BaseController(ISiteService siteService)
    {
        _siteService = siteService; // this never gets hit..
    }

    protected override void Initialize(RequestContext rc)
    {
        string host = ((rc.HttpContext).Request).Url.Host; 
        Site site = _siteService.GetSiteByHost(host); // so _siteService is null...

        base.Initialize(rc);
    }
}

Can somebody tell me why this would be the case? 有人可以告诉我为什么会这样吗? What do I need to do to get this constructor to execute? 我需要做什么才能使此构造函数执行?

All controllers that implement BaseController have constructors that take various parameters supplied by StructureMap, and all those constructors are executed. 所有实现BaseController的控制器的构造函数均采用StructureMap提供的各种参数,并且所有这些构造函数均被执行。

I don't know if it's relevant but this is how I'm configuring StructureMap for my dependency injection. 我不知道它是否相关,但这就是我为依赖注入配置StructureMap的方式。

private void ConfigureNonOptionalDependencies()
{
    // all other dependencies are registered same as this, 
    // and the constructors all get hit
    ForRequestedType<ISiteService>()
        .TheDefaultIsConcreteType<SiteService>();
}

I'm unfamiliar with StructureMap, so I don't know if it has anything to do with this issue, or if it's more of an MVC problem. 我不熟悉StructureMap,所以我不知道它是否与此问题有关,或者更多是MVC问题。 Or is it even possible for this? 还是有可能做到这一点? Thanks 谢谢

edit: 编辑:

also, I've tried this: 另外,我已经尝试过:

public class GroupController : BaseController
{

    private readonly IGroupService _groupService;

    private readonly ISiteService _siteService;

    public GroupController() {}

    public GroupController(
        ISiteService siteService
        ): base(siteService)
    {
        _siteService = siteService;
    }
}

Do your subclass constructors include a call to base ? 您的子类构造函数是否包含对base的调用?

eg 例如

public MyController(ISiteService siteService) : base(siteService)
{
    //do some MyController specific stuff
}

If you are already loading the controllers via structuremap, why not just eliminiate the parameterless constructor? 如果您已经在通过Structuremap加载控制器,为什么不仅仅消除无参数构造函数呢? You don't need it anymore and it is probably confusing something somewheres . 您不再需要它了,它可能会使某些地方有些混乱。 . .

Structure Map NuGet is different for MVC and API projects. 结构图NuGet对于MVC和API项目是不同的。 Seems like you have installed NuGet only for MVC Project. 好像您只为MVC项目安装了NuGet。

Try Installing StructureMap.WebApi2 尝试安装StructureMap.WebApi2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM