在 Autofac 中注册第三方 class,其构造函数从另一个服务获取值

Registering a third party class in Autofac whose constructor take in values from another service

我正在使用 Microsoft.Azure.ServiceBus 命名空间中的 IQueueClient 接口。

这是我的代码

public HomeControllerBL(IApplicationSettings appSettings)
{
    _appSettings = appSettings;
}

这是我的 IApplicationSettings 界面

public interface IApplicationSettings
{
    string GetServiceBusConnectionString();    
    string GetQueueName();
}

现在用于创建 QueueClient

的对象
IQueueClient queueClient = new QueueClient(appSettings.GetServiceBusConnectionString(), appSettings.GetQueueName());

所以 IQueueClient 依赖于 IApplicationSettings

有没有一种方法可以将 IQueueClientIApplicationSettings 都注册到 Autofac 作为 HomeControllerBL

的依赖项

这些行的内容:-

builder.RegisterType<ApplicationSettings>()
    .As<IApplicationSettings>()
    .InstancePerLifetimeScope();

builder.RegisterType<QueueClient>()
    .As<IQueueClient>().WithParameters(new List<Parameter>() { How to access Applicationsettings methods here ???  })
    .InstancePerLifetimeScope();

引用Lambda Expression Components

Reflection is a pretty good default choice for component creation. Things get messy, though, when component creation logic goes beyond a simple constructor call.

Autofac can accept a delegate or lambda expression to be used as a component creator:

builder.Register(c => {
    IApplicationSettings appSettings = c.Resolve<IApplicationSettings>();
    IQueueClient queueClient = new QueueClient(appSettings.GetServiceBusConnectionString(), appSettings.GetQueueName());
    return queueClient;
})
.As<IQueueClient>()
.InstancePerLifetimeScope();

The parameter c provided to the expression is the component context (an IComponentContext object) in which the component is being created. You can use this to resolve other values from the container to assist in creating your component. It is important to use this rather than a closure to access the container so that deterministic disposal and nested containers can be supported correctly.

所以现在控制器可以明确地依赖IQueueClient

private readonly IQueueClient queueClient;

public HomeControllerBL(IQueueClient queueClient) {
    this.queueClient = queueClient;
}