因此,我知道如何设置控制器,以便可以接受注入到控制器中的LinkGenerator。我不知道如何在启动时使用LinkGenerator注入控制器。
控制器
protected readonly LinkGenerator _linkGenerator;
public SomeController(config config, LinkGenerator linkGenerator)
{
config = Config;
_linkGenerator = linkGenerator;
}
启动-ConfigureServices
Controllers.SomeController someController = new
Controllers.SomeController(config, linkGenerator); //how do I get an
instance of link generator here.
services.AddSingleton(someController);
我在启动的Configure方法中尝试过此操作,但是ConfigureServices在Configure之前运行
app.Use(async (context, next) =>
{
linkGenerator = context.RequestServices.GetService<LinkGenerator>();
});
我想念什么?
答案 0 :(得分:0)
在Startup.cs的ConfigureServices中尝试以下方法
public Startup(IConfiguration configuration , IHttpContextAccessor accessor)
{
Configuration = configuration;
_accessor = accessor;
}
public readonly IHttpContextAccessor _accessor;
public IConfiguration Configuration { get; }
var linkGenerator = _accessor.HttpContext.RequestServices.GetService<LinkGenerator>();
services.AddScoped<LinkGenerator>();
services.AddTransient(ctx =>
new ValuesController(linkGenerator));
控制器
private readonly LinkGenerator _linkGenerator;
public ValuesController(LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
}
参考:https://andrewlock.net/controller-activation-and-dependency-injection-in-asp-net-core-mvc/