使用可选参数对象注册 autofac 组件

Register autofac component with optional parameters object

我想在构造函数中注册一个带有可选参数的组件。 我看到 passing optional parameter to autofac 看起来不错,但不确定如何使用 xml 配置实现它。

假设这是我的代码:

public Service(IRepo repo, IEnumerable<IServiceVisitor> serviceVisitors = null)
{
    this._repo= repo;
    _serviceVisitors= serviceVisitors;
}

我想注入复杂类型 IServiceVisitor

为了将 IServiceVisitor 注入 Service,您只需注册它们。

<configuration>
  <autofac defaultAssembly="App">    
    <components>
      <component type="App.Service" 
                 service="App.IService"  />  
      <component type="App.ServiceVisitor1" 
                 service="App.IServiceVisitor"  />  
      <component type="App.ServiceVisitor2" 
                 service="App.IServiceVisitor"  />  
    </components>    
  </autofac>
</configuration>

在这种情况下,您不需要指定 IEnumerable<IServiceVisitor> 的默认值。如果没有注册 IServiceVisitorAutofac 将自动生成一个空数组。

public Service(IRepo repo, IEnumerable<IServiceVisitor> serviceVisitors)
{ /* ... */ }

如果您不需要 IEnumerable<IServiceVisitor> 但需要可选的 IServiceVisitor 您只需在构造函数中使用 = null

将其声明为可选
public Service(IRepo repo, IServiceVisitor serviceVisitor = null)
{ /* ... */ }