您如何在Autofac中提供特定的注册作为其他注册的参数?

问题描述 投票:0回答:1

您能否提供有关如何将某些引用传递给其他注册的指南?

//registration of 1st http client
    builder.RegisterType<HttpClient>()
      //.Keyed<HttpMessageInvoker>("authHttpClient")
     .WithProperties(new[] { new NamedPropertyParameter("PooledConnectionLifetime", 2 })
     .WithProperties(new[] { new NamedPropertyParameter("BaseAddress", "whatever"))})
     .SingleInstance();

//registration of 2nd httpclient
    builder.RegisterType<HttpClient>()
     .Keyed<HttpMessageInvoker>("dynamicsHttpClient")
     .WithProperties(new[] { new NamedPropertyParameter("PooledConnectionLifetime", 20) })
     .WithProperties(new[] { new NamedPropertyParameter("BaseAddress", "other something" })
    .SingleInstance();


// **I need to  do the registration of type and pass the 1st httpClient registration**
builder.RegisterType<DynamicsAuthApiGateway>()
    .As<IDynamicsAuthApiGateway>()

// **I need to do the registration of type pass 2nd instance of httpClient registration**
builder.RegisterType<DynamicsApiGateway>()
                .As<IDynamicsApiGateway>()
                .SingleInstance();

//Method ctor's
//DynamicsAuthApiGateway(**HttpClient client**, DynamicsAuthApiGatewaySettings apiGatewaySettings)
//DynamicsApiGateway(**HttpClient client**, Func<HttpResponseMessage, Task> errorHandler = null) 

您能帮上忙吗?

任何帮助将不胜感激?

谢谢,我

autofac autofac-module
1个回答
0
投票

您在使用键控服务的正确轨道上。 Docs here for details and examples.

最简单的方法是使用Autofac.Features.AttributeFilters.KeyFilterAttribute在消费类上标记构造函数。

首先,更新使用者。这是一个例子。

Autofac.Features.AttributeFilters.KeyFilterAttribute

然后注册带密钥的客户端并在使用者上启用属性筛选。

public class DynamicsAuthApiGateway : IDynamicsAuthApiGateway
{
  // KeyFilterAttribute on the parameter
  public DynamicsAuthApiGateway([KeyFilter("authHttpClient")] HttpClient client)
  {
    // ...
  }
}

您必须选择属性过滤,因为如果不需要,这会带来额外的性能开销。如果不放置// Don't forget // using Autofac.Features.AttributeFilters; // at the top... then: // Register the HttpClient instances with keys // and be sure the key is on the same type/interface // as you see in the constructor of the consumer. builder.RegisterType<HttpClient>() .Keyed<HttpClient>("authHttpClient") .SingleInstance(); builder.RegisterType<HttpClient>() .Keyed<HttpClient>("dynamicsHttpClient") .SingleInstance(); // Register the consumers and enable attribute filters builder.RegisterType<DynamicsAuthApiGateway>() .As<IDynamicsAuthApiGateway>() .WithAttributeFiltering(); builder.RegisterType<DynamicsApiGateway>() .As<IDynamicsApiGateway>() .SingleInstance() .WithAttributeFiltering(); 部分,则不会进行过滤。

[如果您不希望在类中使用该属性(例如,您希望避免将Autofac绑定到事物中,那么这会有点困难-您需要使用WithAttributeFiltering()ResolvedParameter)。

这看起来会更像这样(我有点想把它写在脑海上,所以如果有错字或其他东西,您会收到警告,但基本上应该是……)...

docs here

它不是很干净,但是可以使Autofac引用不被消费者使用(如果重要的话)。如果您经常使用它,则可以编写自己的扩展方法以使其更容易。我将其留给读者练习。

© www.soinside.com 2019 - 2024. All rights reserved.