问题描述
所以我知道如何设置我的控制器,以便我可以接受注入控制器的 LinkGenerator.我不知道如何在启动时使用 LinkGenerator 注入我的控制器.
So I know how to setup my controller so that I can accept a LinkGenerator injected into the controller. What I can't figure out is how do I inject my controller at startup with a LinkGenerator.
控制器
protected readonly LinkGenerator _linkGenerator;
public SomeController(config config, LinkGenerator linkGenerator)
{
config = Config;
_linkGenerator = linkGenerator;
}
启动 - 配置服务
Controllers.SomeController someController = new
Controllers.SomeController(config, linkGenerator); //how do I get an
instance of link generator here.
services.AddSingleton(someController);
services.AddSingleton(someController);
我在启动的Configure方法中试过这个,但是ConfigureServices在Configure之前运行
I tried this in the Configure method of startup, but ConfigureServices runs before Configure
app.Use(async (context, next) =>
{
linkGenerator = context.RequestServices.GetService<LinkGenerator>();
});
我错过了什么?
推荐答案
在Startup.cs的ConfigureServices中尝试以下方法
Try the following approach in ConfigureServices of Startup.cs
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/
这篇关于不知道如何注入 LinkGenerator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!