C# 选项模式,消费者对象选择.NET Core中依赖项的选项
我有一个C# 选项模式,消费者对象选择.NET Core中依赖项的选项,c#,design-patterns,dependency-injection,.net-core,options,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; } }
IRemoteCaller
由HttpCaller
实现,它需要HttpCallerOptions
进行如下实例化
public class HttpCaller : IRemoteCaller {
private HttpCallerOptions _options;
public HttpCaller(IOptions<HttpCallerOptions> options) {
_options = options.Value;
}
}
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>();
}
我的启动将注册我的服务并配置选项,如下所示
public class HttpCaller : IRemoteCaller {
private HttpCallerOptions _options;
public HttpCaller(IOptions<HttpCallerOptions> options) {
_options = options.Value;
}
}
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>();
}
public void配置服务(IServiceCollection服务){
Configure(o=>o.SomeProps);//默认选项
services.AddTransient();
服务。配置(
o=>o.RuleServiceSpecificHttpOptions);//规则服务的特定选项
配置(o=>o.RuleServiceOptions);
services.Configure();
}
现在我有两个用于HttpCaller
的命名选项,我想在RuleService
中注入HttpCaller
实例时,注入特定于RuleService
的选项。当我没有在规则服务
中使用它时,应该为默认
选项配置HttpCaller
实例
如何实现这一点?我假设HttpCaller中有一种方法,它利用RuleService和其他服务所需的公共选项?为什么不在方法内部选择适当的选项,通过传入值,该值可以让方法决定谁在调用该方法。您可以在服务集合中查找注册工厂,因此根据参数,可以返回所需的
HttpCallerOptions
@Ytan,HttpCaller
中的方法将是Post、Get、,等等,我只想允许有效负载作为参数传入。另外,我希望在HttpCaller
的构造函数中创建System.Net.HttpClient
实例,以便方法更干净@user1672994,您有任何参考资料吗?谢谢@Steven,您是否可以添加新的标记选项模式,而不是设计模式和选项标记?由于我的分数很低,这是不允许的。谢谢