2

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

假设这是我的代码:

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

我想注入复杂类型IServiceVisitor

4

1 回答 1

2

为了将IServiceVisitors 注入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>. 如果没有注册,Autofac会自动生成一个空数组。IServiceVisitor

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

如果您不需要 aIEnumerable<IServiceVisitor>但需要一个可选项IServiceVisitor,则只需在构造函数中将其声明为可选项= null

public Service(IRepo repo, IServiceVisitor serviceVisitor = null)
{ /* ... */ }
于 2016-07-04T10:13:09.810 回答