2

I would like to register a component with an optional parameter in the constructor. I saw passing optional parameter to autofac that looks good but not sure how I can implement this with xml configuration.

Let's say this is my code:

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

and I want to inject the complex type IServiceVisitor.

Kristof U.
  • 1,263
  • 10
  • 17
Daniel Rapaport
  • 375
  • 2
  • 18

1 Answers1

2

In order to inject IServiceVisitors into Service you only have to register them.

<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>

In this case you don't need to specify the default value of IEnumerable<IServiceVisitor>. Autofac will automatically generates an empty array if no IServiceVisitor is registered.

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

If you don't need a IEnumerable<IServiceVisitor> but need an optional IServiceVisitor you only have to declare it as optional in the constructor using = null

public Service(IRepo repo, IServiceVisitor serviceVisitor = null)
{ /* ... */ }
Cyril Durand
  • 15,834
  • 5
  • 54
  • 62