简体   繁体   English

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

[英]Injecting NamedOptions across the assemblies in an asp.net core project?

I have configured a NamedOption in ConfigureServices method of Startup.cs like following:我在Startup.csConfigureServices方法中配置了一个NamedOption ,如下所示:

services.Configure<MyOpts>("myOpts", 
   opts => configuration.Bind("myOpts", opts));

I have a controller action in asp.net core api like following:我在asp.net core api 中有一个控制器操作,如下所示:

public async Task<IActionResult> Insert(CreateUserCommand command)
{
    var id = await Mediator.Send(command);

    return Ok(id);
}

This is my CreateUserCommand :这是我的CreateUserCommand

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; }
}

When client hits my api, I want MyOpts object injected in CreateUserCommand(IOptionsSnapshot<MyOpts> opts) .当客户端访问我的 api 时,我希望在CreateUserCommand(IOptionsSnapshot<MyOpts> opts)中注入MyOpts对象。 CreateUserCommand is in the assembly other than asp.net core project. CreateUserCommand 在 asp.net 核心项目以外的程序集中。 Is it possible to achieve this behaviour?是否有可能实现这种行为?

If you register also Commands in DI then yes (You usually don't register commands with DI), but based what I see CreateUserCommand is a payload (in your case) so I assume that you don't register it and it will not work (not only in a different assemblies but also in same assemblies).如果您还在 DI 中注册了命令,那么是的(您通常不使用 DI 注册命令),但基于我所看到的 CreateUserCommand 是一个有效负载(在您的情况下)所以我假设您没有注册它并且它不会工作(不仅在不同的程序集中,而且在相同的程序集中)。 Because you use Mediator I assume that you have a handler for CreateUserCommand and I think there you can inject your configuration and it will work.因为你使用 Mediator,所以我假设你有一个 CreateUserCommand 的处理程序,我认为你可以在那里注入你的配置并且它会起作用。

Yes, the Default ASP.NET Core DI supports the Injection across the multiple assemblies when done right.是的,如果正确完成,默认的 ASP.NET Core DI 支持跨多个程序集的注入。

Please refer the nice article for more details.有关更多详细信息,请参阅这篇不错的文章。

https://asp.net-hacker.rocks/2017/03/06/using-dependency-injection-in-multiple-projects.html https://asp.net-hacker.rocks/2017/03/06/using-dependency-injection-in-multiple-projects.html

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM