Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.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
C# 如何将依赖项从自定义中间件传递到控制器?_C#_Asp.net Core_Dependency Injection_.net Core_Middleware - Fatal编程技术网

C# 如何将依赖项从自定义中间件传递到控制器?

C# 如何将依赖项从自定义中间件传递到控制器?,c#,asp.net-core,dependency-injection,.net-core,middleware,C#,Asp.net Core,Dependency Injection,.net Core,Middleware,我有一个自定义中间件,我想从中添加一个作用域依赖项 public class MyMiddleware { private readonly RequestDelegate _next; public MyMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext httpContext, IOptions

我有一个自定义中间件,我想从中添加一个作用域依赖项

public class MyMiddleware {
    private readonly RequestDelegate _next;

    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext,
        IOptionsSnapshot<ApiClientHttpSettings> settings,
        IServiceCollection services)
    {
        services.AddScoped<ICustomer>(new Customer());

        await _next(httpContext);
    }
}
但是在中间件中,
IServiceCollection
无法解析。 我想这样做是因为有很多逻辑来解决所涉及的DI

我也可以尝试在
ConfigureServices
内部执行操作,但这样我就无法访问每个请求所需的
IOptionsSnapshot设置

任何指向正确方向的指针都是值得赞赏的

我也可以尝试在
ConfigureServices
内部执行,但这样我就无法访问每个请求所需的
IOptionsSnapshot
设置

以下是如何在自定义服务中访问
IOptionsSnapshot
。完整的来源是

创建你的设置类

public class SupplyApiClientHttpSettings
{
    public string SomeValue { get; set; }
}
在配置中为其添加一个值(例如在
appsettings.json

定义您的服务并将
IOptionsSnapshot
注入其中

public class CustomerService
{
    private readonly SupplyApiClientHttpSettings settings;

    public CustomerService(IOptionsSnapshot<SupplyApiClientHttpSettings> options)
    {
        this.settings = options.Value;
    }

    public Customer GetCustomer()
    {
        return new Customer
        {
            SomeValue = settings.SomeValue
        };
    }
}
将服务注入控制器。使用该服务向客户提供最新的选项快照

public class CustomerController : Controller
{
    private readonly CustomerService customerService;

    public CustomerController(CustomerService customerService)
    {
        this.customerService = customerService;
    }

    public IActionResult Index() 
    {
        return Json(customerService.GetCustomer());
    }
}

这是完整的资料来源。

答案非常简单和接近。以下是我必须做的:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ICustomer>(provider => {
        var settings = Configuration.GetSection("ApiClientHttpSettings").Get<ApiClientHttpSettings>();
        return new Customer(settings.Name, settings.Age);
    });
}
public void配置服务(IServiceCollection服务)
{
services.AddScoped(provider=>{
var settings=Configuration.GetSection(“ApiClientHttpSettings”).Get();
返回新客户(settings.Name、settings.Age);
});
}
以上为我勾选了所有框:

  • 每个请求的新实例
  • 能够在请求时读取更新的配置
  • 根据自定义逻辑创建实例

  • 你有点前后颠倒了。这是中间件执行的代码,DI配置应该在安装程序中完成。
    services.AddScoped(new Customer())应在启动时在
    ConfigureServices
    中完成。cs@DavidG设置是指
    ConfigureServices
    method?@p3tch我希望能够做到这一点,但是我需要在每个请求上访问更新的配置
    IOptionsSnapshot
    ,因为将对的实例的属性进行一些更改
    iccustomer
    基于请求。如果每个请求的
    iccustomer
    都在更改,则该对象需要提供给它的选项。
    public class Startup
    {
        IConfiguration Configuration;
    
        public Startup()
        {
            Configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<SupplyApiClientHttpSettings>(Configuration);
            services.AddScoped<CustomerService>();
            services.AddMvc();
        }
    
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvcWithDefaultRoute();
        }
    }
    
    public class CustomerController : Controller
    {
        private readonly CustomerService customerService;
    
        public CustomerController(CustomerService customerService)
        {
            this.customerService = customerService;
        }
    
        public IActionResult Index() 
        {
            return Json(customerService.GetCustomer());
        }
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<ICustomer>(provider => {
            var settings = Configuration.GetSection("ApiClientHttpSettings").Get<ApiClientHttpSettings>();
            return new Customer(settings.Name, settings.Age);
        });
    }