简体   繁体   English

ASP.NET Core DI不同的选项实例取决于请求的类

[英]ASP.NET Core DI different options instance depending on requesting class

I've used Autofac in the past and while sometimes it can be a bit complicated it has never lacked in features I needed. 我过去曾经使用过Autofac,尽管有时它可能有点复杂,但它从来没有缺少我需要的功能。 Now I'm trying to use the built-in dependency injection in ASP.NET Core and am having trouble achieving the following: 现在,我试图在ASP.NET Core中使用内置的依赖项注入,并且在实现以下目标时遇到了麻烦:

Startup.cs 启动文件

public void ConfigureServices(IServiceCollection services) {
  // Use these settings by default
  services.Configure<EmailerSettings>(Configuration.GetSettings("DefaultEmailer"));

  // Would like to specify different settings that apply to the SpecialEmailer class only
  //services.Configure<EmailerSettings>(Configuration.GetSettings("SpecialEmailer"));
}

Classes that depend on DI 依赖于DI的类

public class Emailer {
    public Emailer(IOptions<EmailerSettings> settings) {
       // Should get the default settings
    }
}

public class SpecialEmailer {
    public SpecialEmailer(IOptions<EmailerSettings> settings) {
       // Should get the special settings
    }
}

Is there any way to do this with the out of the box DI? 开箱即用的DI有什么办法做到这一点? I could of course create SpecialEmailerSettings and use that in the SpecialEmailer class, but the structure is identical so I'd like to reuse if possible. 我当然可以创建SpecialEmailerSettings并在SpecialEmailer类中使用它,但是结构是相同的,因此我想尽可能地重用。

There are several ways to do that, but I don't think that any of them is elegant as you're hoping for. 有几种方法可以做到这一点,但我认为您所希望的其中任何一种都不优雅。 I guess your best bet is to create another settings model SpecialEmailerSettings that inherits from EmailerSettings . 我想你最好的选择是创建另一个设置模式SpecialEmailerSettings从继承EmailerSettings I know that you've already thought of this and you wanted to reuse, but I think inheritance is one way of reusing. 我知道您已经想到了这一点,并且想要重用,但是我认为继承是重用的一种方式。 It's just one extra line: 这只是另外一行:

public class SpecialEmailerSettings : EmailerSettings { }

Then load it like this: 然后像这样加载它:

services.Configure<EmailerSettings>(Configuration.GetSettings("DefaultEmailer"));
services.Configure<SpecialEmailerSettings>(Configuration.GetSettings("SpecialEmailer"));

And finally use it in your class: 最后在课堂上使用它:

public class SpecialEmailer {
    public SpecialEmailer(IOptions<SpecialEmailerSettings> settings) {
       // Should get the special settings
    }
}

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

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