Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net core Can';我不知道如何注入LinkGenerator_.net Core_Asp.net Core Webapi - Fatal编程技术网

.net core Can';我不知道如何注入LinkGenerator

.net core Can';我不知道如何注入LinkGenerator,.net-core,asp.net-core-webapi,.net Core,Asp.net Core Webapi,因此,我知道如何设置控制器,以便可以接受注入控制器的链接生成器。我不明白的是,如何在启动时向控制器注入LinkGenerator 控制器 protected readonly LinkGenerator _linkGenerator; public SomeController(config config, LinkGenerator linkGenerator) { config = Config; _linkGenerator = linkGenerator

因此,我知道如何设置控制器,以便可以接受注入控制器的链接生成器。我不明白的是,如何在启动时向控制器注入LinkGenerator

控制器

protected readonly LinkGenerator _linkGenerator;

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

public ValuesController(LinkGenerator linkGenerator)
{
     _linkGenerator = linkGenerator;
}
启动-配置服务

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

我在启动的Configure方法中尝试了这一点,但ConfigureServices在Configure之前运行

app.Use(async (context, next) =>
{
     linkGenerator = context.RequestServices.GetService<LinkGenerator>();
});
app.Use(异步(上下文,下一步)=>
{
linkGenerator=context.RequestServices.GetService();
});

我缺少什么?

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

参考:

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

参考资料:

访问者来自哪里?我是.Net Core的新手,所以可能只是缺少了一些东西。我遇到了此错误,无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务\u accessor来自哪里?我是.Net Core的新手,因此可能只是缺少了一些东西。我遇到此错误,无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务