C# 在asp.net核心项目中跨程序集注入NamedOptions?

C# 在asp.net核心项目中跨程序集注入NamedOptions?,c#,asp.net-core,.net-core,dependency-injection,C#,Asp.net Core,.net Core,Dependency Injection,我在Startup.cs的ConfigureServices方法中配置了NamedOption,如下所示: services.Configure<MyOpts>("myOpts", opts => configuration.Bind("myOpts", opts)); public async Task<IActionResult> Insert(CreateUserCommand command) { var id = await Mediat

我在Startup.cs的ConfigureServices方法中配置了NamedOption,如下所示:

services.Configure<MyOpts>("myOpts", 
   opts => configuration.Bind("myOpts", opts));
public async Task<IActionResult> Insert(CreateUserCommand command)
{
    var id = await Mediator.Send(command);

    return Ok(id);
}
这是我的CreateUserCommand:


当客户端访问我的api时,我希望将MyOpts对象注入CreateUserCommandIOptionsSnapshot选项中。CreateUserCommand位于asp.net核心项目以外的程序集中。是否有可能实现此行为?

是的,默认的ASP.NET Core DI在正确完成时支持跨多个程序集的注入

请参考nice文章了解更多详细信息


希望这有帮助

如果您也在DI中注册命令,那么是的,您通常不会在DI中注册命令,但是根据我所看到的CreateUserCommand在您的情况下是一个有效负载,因此我假设您不会注册它,并且它不仅在不同的程序集中有效,而且在相同的程序集中也有效。
因为您使用了Mediator,所以我假设您有一个CreateUserCommand的处理程序,我认为您可以在那里注入您的配置,它将正常工作。

正是如此。你是对的。我正在使用中介模式,是的,我将它注入了处理程序类中。工作得很有魅力!T
public class CreateUserCommand
{
    private MyOpts opts { get; }

    public CreateUserCommand(IOptionsSnapshot<MyOpts> opts)
    {
        this.opts = opts.Get("myOpts");
    }

    public long UserId { get; set; }
    public string Username { get; set; }
    public string FirstName { get; set; }
}