Injection of IUrlHelper in ASP.NET Core

后端 未结 6 1953
借酒劲吻你
借酒劲吻你 2020-12-05 17:29

In RC1, IUrlHelper could be injected in services (with services.AddMvc() in startup class)

This doesn\'t work anymore in <

6条回答
  •  囚心锁ツ
    2020-12-05 17:49

    For ASP.NET Core RC2 there is an issue for this on the github repo. Instead of injecting the IUrlHelper, take an IUrlHelperFactory. It also sounds like you'd need the IActionContextAccessor injected as a Controller no longer has a public property ActionContext.

    Register the dependency:

    services.AddSingleton();
    

    Then depend on it:

    public SomeService(IUrlHelperFactory urlHelperFactory,
                       IActionContextAccessor actionContextAccessor)
    {
    
        var urlHelper =
            urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
    }
    

    Then use it as you see fit.

提交回复
热议问题