如何在启动 class 时传递一些 属性 并在控制器上初始化它

How to pass some property on startup class and initialize it on controller

我有一个 .net core 3.1 后台应用程序,我在其中根据实现跨越 kestrel 服务器。 我需要的是在启动时配置一些属性(比方说int channel id)

启动

internal class Startup
{
    internal static IHostBuilder CreateHostBuilder(MyConfigurations _objSettings)
    {
    
        //_objSettings.channelId need to be assigned to CallBackController channelID
        return Host
            .CreateDefaultBuilder()
            .ConfigureWebHostDefaults(webBuilder => 
                webBuilder.UseUrls(_objSettings.CallbackLocalListener)
            )
            .UseStartup<Startup>());
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options => options.RespectBrowserAcceptHeader = true);
        services.Configure<ForwardedHeadersOptions>(options =>
        {
            options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseForwardedHeaders();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

控制器

[Produces("application/json")]
public class CallBackController : ControllerBase
{          
    int channelId = 0;//this need to be initializes 

    public IActionResult Receive()
    {
        IActionResult result = null;
       
        return result;
    }
}

我需要这个,因为 class 多个实例将在其他端口上启动 kestrel 实例,监听不同的流量。在收到请求时,我需要那个频道 ID 来初始化一些东西

创建一个类型来存储所需的选项

public class ChannelOptions {
    public int ChannelId { get; set; }
}

并在 Startup 中使用 convivence 成员进行配置

internal static IHostBuilder CreateHostBuilder(MyConfigurations _objSettings) {        
    return Host
        .CreateDefaultBuilder()
        .ConfigureServices(services => 
            services.AddSingleton(
                new ChannelOptions {
                    ChannelId = _objSettings.channelID
                }
            )
        )
        .ConfigureWebHostDefaults(webBuilder => 
            webBuilder.UseUrls(_objSettings.CallbackLocalListener)
        )
        .UseStartup<Startup>());
}

最后,将选项作为依赖显式注入控制器

[Produces("application/json")]
public class CallBackController : ControllerBase {

    private readonly int channelId = 0;

    public CallBackController(ChannelOptions options) {
        channelId = options?.ChannelId ?? 0;
    }

    public IActionResult Receive() {
        IActionResult result = null;
       
        return result;
    }
    
    //...
}