[英]Create multiple instances of same dependency w/ different configuration
I have an application ( IJobInit ) that uses a list from JSON settings to create multiple instances of a class ( IJob ). 我有一个应用程序( IJobInit ),它使用JSON设置中的列表来创建一个类( IJob )的多个实例。 This class does some work using two other dependencies, IInputClient and IOutputClient .
此类使用其他两个依赖项IInputClient和IOutputClient进行一些工作。 It uses M.Extensions.DependencyInjection to create a container which is handed off to AutoFac to create an IContainer.
它使用M.Extensions.DependencyInjection创建一个容器,该容器将移交给AutoFac以创建一个IContainer。
IJobInit(IContainer container)
I would like IInputClient to be configured different for each instance of IJob. 我希望为每个IJob实例配置不同的IInputClient。 Speficially, I'd like to pass in a secret for it to use.
具体来说,我想传递一个秘密供其使用。 The result would be:
结果将是:
IInputClient(HttpClient client)
where HttpClient is configured using ConfigureHttpClient such that IJob does not know that it is pre-authenticated. 使用ConfigureHttpClient配置 HttpClient的位置,以使IJob不知道它已预先认证。 This would also be suitable:
这也将是合适的:
IInputClient(ISecretProvider secretsProvider, string secretName)
The end result is three instances of IJob with IInputClient configured differently. 最终结果是IJob的三个实例的IInputClient配置不同。
IJob(IInputClient inputClient1, IOutputClient outputClient)
IJob(IInputClient inputClient2, IOutputClient outputClient)
IJob(IInputClient inputClient3, IOutputClient outputClient)
How do I achieve this? 我该如何实现? I was looking at Autofac scopes but those controlwhen an instance is created without any control over its configuration (unless I missed it).
我一直在查看Autofac范围,但是这些控件在创建实例时对它们的配置没有任何控制(除非我错过了它)。
A colleague suggested that I could host each instance of IJob in its own process with its own configuration which is possible but I'm trying to host all the jobs in a single Azure Function and use the list in config to create the inner jobs. 一位同事建议我能举办IJob的每个实例在自己的进程有其自己的配置是可能的,但我试图运行所有的工作在一个单一的Azure的功能和使用列表中配置创造就业内。
Thanks! 谢谢!
I'm not totally happy with this solution but it works for now. 我对这种解决方案并不完全满意,但它现在可以使用。
private async Task<IInputClient> GetClientAsync(string secretId)
{
HttpClient httpClient = this.httpClientFactory.CreateClient();
string secret = await this.secretsProvider.GetSecretAsync(secretId);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Concat(":", secret))));
return this.scope.Resolve<IInputClient>(new TypedParameter(typeof(HttpClient), httpClient));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.