不知道如何注入 LinkGenerator [英] Can't figure out how to inject LinkGenerator

查看:36
本文介绍了不知道如何注入 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;
}

启动 - 配置服务

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天全站免登陆