用可选参数对象注册autoface组件
本文关键字:注册 autoface 组件 对象 参数 | 更新日期: 2023-09-27 17:54:08
我想在构造函数中注册一个带有可选参数的组件。我看到将可选参数传递给autoface,看起来不错,但不确定如何用xml配置实现这一点。
假设这是我的代码:
public Service(IRepo repo, IEnumerable<IServiceVisitor> serviceVisitors = null)
{
this._repo= repo;
_serviceVisitors= serviceVisitors;
}
,我想注入复杂类型IServiceVisitor
为了将IServiceVisitor
s注入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)
{ /* ... */ }
如果你不需要IEnumerable<IServiceVisitor>
,但需要一个可选的IServiceVisitor
,你只需要在构造函数中使用= null
将其声明为可选的
public Service(IRepo repo, IServiceVisitor serviceVisitor = null)
{ /* ... */ }