简体   繁体   中英

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. Now I'm trying to use the built-in dependency injection in ASP.NET Core and am having trouble achieving the following:

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

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? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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