Can't figure out how to inject LinkGenerator

假装没事ソ 提交于 2021-01-28 11:02:14

问题


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.

Controller

protected readonly LinkGenerator _linkGenerator;

public SomeController(config config, LinkGenerator linkGenerator)
{
        config = Config;
        _linkGenerator = linkGenerator;
}

StartUp - ConfigureServices

Controllers.SomeController someController = new 
Controllers.SomeController(config, linkGenerator); //how do I get an 
instance of link generator here.

services.AddSingleton(someController);

I tried this in the Configure method of startup, but ConfigureServices runs before Configure

app.Use(async (context, next) =>
{
     linkGenerator = context.RequestServices.GetService<LinkGenerator>();
});

What am I missing?


回答1:


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));

Controller

private readonly LinkGenerator _linkGenerator;

public ValuesController(LinkGenerator linkGenerator)
{
     _linkGenerator = linkGenerator;
}

Reference :https://andrewlock.net/controller-activation-and-dependency-injection-in-asp-net-core-mvc/



来源:https://stackoverflow.com/questions/56653105/cant-figure-out-how-to-inject-linkgenerator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!