问题
In RC1, IUrlHelper
could be injected in services (with services.AddMvc()
in startup class)
This doesn't work anymore in RC2. Does anybody know how to do it in RC2 as just newing up a UrlHelper
requires an ActionContext
object. Don't know how to get that outside a controller.
回答1:
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<IActionContextAccessor, ActionContextAccessor>();
Then depend on it:
public SomeService(IUrlHelperFactory urlHelperFactory,
IActionContextAccessor actionContextAccessor)
{
var urlHelper =
urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
}
Then use it as you see fit.
回答2:
For Net Core 2.0
Add this after service.AddMvc()
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(factory =>
{
var actionContext = factory.GetService<IActionContextAccessor>()
.ActionContext;
return new UrlHelper(actionContext);
});
回答3:
ASP.NET Core 2.0
Install
PM> Install-Package AspNetCore.IServiceCollection.AddIUrlHelper
Use
public void ConfigureServices(IServiceCollection services)
{
...
services.AddUrlHelper();
...
}
Disclaimer: author of this package
回答4:
For .Net Core 2.0
services.AddMvc();
services.AddScoped<IUrlHelper>(x =>
{
var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
var factory = x.GetRequiredService<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext);
});
回答5:
For ASP.Net Core 2.0 you must not inject an IUrlHelper. It’s available as a property of the controller. ControllerBase.Url is an IUrlHelper instance.
来源:https://stackoverflow.com/questions/37322076/injection-of-iurlhelper-in-asp-net-core