lundi 2 décembre 2019

Options pattern with consumer object selecting the option for the dependency dot net core

I have a IRemoteCaller which is implemented by HttpCaller and it needs HttpCallerOptions for instantiating as like below,

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

Now I have a service RulesService implementing IRulesService with the RulesServiceOptions and is dependent on IRemoteCaller as shown below,

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

My startup will register my service and configure options as like below,

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

Now I have two named options for HttpCaller, I want to inject the options specific to the RuleService when the HttpCaller instance is injected in RuleService. When I am not using it within RuleService, the HttpCaller instance should be configured for Default options.

How to achieve this?

Aucun commentaire:

Enregistrer un commentaire