Microsoft.组合(MEF2)约定和开放泛型



我有一个类型

public class Queue<T> : IQueue
{
....
}

我可以通过以下方式导出它

[Export(typeof(Queue<>))]

这将使我能够导入

[Import] Queue<StockController>
[Import] Queue<FileController>

但是,我想将这些类型导入为

[ImportMany] IQueue

如果不为每个队列创建具体类型,这似乎是不可能的。

我想使用约定来提供这些导出,并为每个导出添加元数据。我对如何添加元数据很好,但我不确定如何提供导出。本质上我想要的是类似的东西(伪代码(

conventions.
    ForType(typeof(Queue<StockContoller>)).Export<IQueue>(x => x.AddMetadata("Name", "StockQueue")
    ForType(typeof(Queue<FileContoller>)).Export<IQueue>(x => x.AddMetadata("Name", "FileQueue")

但是除非我实际为每个队列创建具体类型,否则这不起作用,这是我不想做的。

有没有办法做到这一点?

事实证明,解决方案分为两部分。首先,将部件添加到容器中,然后定义约定。下面是实现此目的的扩展方法。

public static ContainerConfiguration WithQueue(
            this ContainerConfiguration config,
            Type queueType,
            string queueName)
        {
            var conventions = new ConventionBuilder();
            conventions
                .ForType(queueType)
                .Export<IQueue>(x => x.AddMetadata("QueueName", queueName));
            return config.WithPart(queueType, conventions);
        }

用法:

CompositionHost container =
    new ContainerConfiguration()
    .WithQueue(typeof(ControllerQueue<StockMovementController>), "StockMovements")
    .WithAssemblies(GetAssemblies())
    .CreateContainer();

(其中 GetAssemblies(( 返回要从中构建容器的程序集(

最新更新