使用消费者对象的选项模式,在.NET Core中选择依赖项的选项

时间:2019-12-02 09:26:46

标签: c# design-patterns dependency-injection .net-core options

我有一个IRemoteCaller,它是由HttpCaller实现的,它需要HttpCallerOptions进行实例化,如下所示,

public class HttpCaller : IRemoteCaller {
    private HttpCallerOptions _options;
    public HttpCaller(IOptions<HttpCallerOptions> options) {
        _options = options.Value;
    }
}

现在我有一个服务RulesServiceIRulesService实现RulesServiceOptions,并且依赖于IRemoteCaller,如下所示,

public class RuleService : IRulesService {
private RulesServiceOptions _options;
private IRemoteCaller _svc;
public RulesService (IOptions<RulesServiceOptions> options, IRemoteCaller svc) {
    _options = options.Value;
    _svc = svc;
}

我的创业公司将注册我的服务并按如下所示配置选项,

public void ConfigureServices(IServiceCollection services) {
    services.Configure<HttpCallerOptions>(o => o.SomeProps); //Default options
    services.AddTransient<IRemoteCaller, HttpCaller>();
    services.Configure<HttpcallerOptions>(
        o => o.RuleServiceSpecificHttpOptions); //Specific options to the RuleService
    services.Configure<RulesServiceOptions>(o => o.RuleServiceOptions);
    services.Configure<IRulesService, RuleService>();
}

现在,我为HttpCaller有两个命名选项,我想在RuleService实例中注入HttpCaller实例时注入特定于RuleService的选项。当我不在RuleService中使用它时,应为HttpCaller选项配置Default实例。

如何实现?

0 个答案:

没有答案