使用Castle Windsor将具有不同实现的List的对象解析为构造函数参数

时间:2015-12-08 12:49:22

标签: c# dependency-injection castle-windsor

我有以下构造函数:

public DataImporterService(IList<IDataValidator> dataValidators,     IList<IDataComparer> dataComparers, IList<IDataStorage> dataStorages)
        {
            _dataValidators = dataValidators;
            _dataComparers = dataComparers;
            _dataStorages = dataStorages;
        }

这是我的注册:

Component.For<IDataComparer>().ImplementedBy<PlanOfRecordComparer>().Named("planOfRecordComparer"),
                Component.For<IDataComparer>().ImplementedBy<PlanOfExecutionComparer>().Named("planOfExecutionComparer"),
                 Component.For<IDataComparer>().ImplementedBy<BomComparer>().Named("bomComparer"),
                Component.For<IDataStorage>().ImplementedBy<PlanOfRecordStorage>().Named("planOfRecordStorage"),
                Component.For<IDataStorage>().ImplementedBy<PlanOfExecutionStorage>().Named("planOfExecutionStorage"),
                Component.For<IDataValidator>().ImplementedBy<PlanOfExecutionValidator>().Named("planOfExecutionValidator"),
                Component.For<IDataValidator>().ImplementedBy<PlanOfRecordValidator>().Named("planOfRecordValidator"),
                Component.For<IDataValidator>().ImplementedBy<BomValidator>().Named("bomValidator")

但是是否可以以另一种方式注册组件,而无需指定IDataComparer,IDataValidator和IDataStorage的每个实现?比如更通用的方式?

2 个答案:

答案 0 :(得分:1)

您是否正在寻找自动注册(基于AKA约定的配置)?

如果是这样,根据my book第10.1.2节中的示例,您应该可以执行类似

的操作
container.Register(AllTypes
    .FromAssemblyContaining<PlanOfExecutionComparer>()
    .BasedOn<IDataComparer>());

答案 1 :(得分:1)

好的,这就是我的工作方式:

我首先使用了collectionresolver:

 container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

注册实施IDataComparerIDataStorageIDataValidator

的所有类
Classes.FromThisAssembly().Where(x => x.Name.EndsWith("Validator")).WithServiceFirstInterface(),
Classes.FromThisAssembly().Where(x => x.Name.EndsWith("Comparer")).WithServiceFirstInterface(),
Classes.FromThisAssembly().Where(x=>x.Name.EndsWith("Storage")).WithServiceFirstInterface()

然后我就能解决我的课程了:

public DataImporterService(IDataValidator[] dataValidators, IDataComparer[] dataComparers, IDataStorage[] dataStorages)
        { }

因此,当Castle Windsor尝试重新调用DataImporterService时,它会抓取所有实现注入接口的类,构造一个数组,将它们放入数组中并提供数组作为依赖项的值。

这在文档here

中提供