无法弄清楚如何注入LinkGenerator [英] Can't figure out how to inject LinkGenerator

查看:101
本文介绍了无法弄清楚如何注入LinkGenerator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我知道如何设置控制器,以便可以接受注入到控制器中的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;
}

启动-ConfigureServices

StartUp - ConfigureServices

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆