繁体   English   中英

MEF 组合使用 ImportMany 和可组合部件的现有实例

[英]MEF composition using ImportMany and existing instances of composable parts

我有以下问题:

在 MEF 上使用ImportMany属性时,MEF 将始终至少创建一个IService接口的实现实例。

由于我已经有一个现有实例(通过在下面的代码中创建一个实例并将其作为组合批处理的一部分进行模拟),我只想在 ServiceHost 实例的 Services 属性中包含此实例。 (当然还有来自具有相同接口实现的其他类型的实例..)

但是 MEF 总是也会创建一个新实例并将其推送到 Services 属性,以便有两个实例 - 我自己创建的一个和 MEF 创建的一个。

如何防止 MEF 创建自己的实例?

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace TestConsole
{
    public interface IService
    {
        int InstanceId { get; }
    }

    public class Program
    {
        public static int counter;

        private static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost();

            DirectoryCatalog catalog = new DirectoryCatalog(".", "*.exe");
            CompositionContainer container = new CompositionContainer(catalog);
            CompositionBatch compositionBatch = new CompositionBatch();

            // create an existing instance
            TestService c = new TestService();
            ComposablePart part = AttributedModelServices.CreatePart(c);
            compositionBatch.AddPart(part);
            Console.WriteLine("existing instance: {0}", c.InstanceId);

            compositionBatch.AddPart(AttributedModelServices.CreatePart(host));

            container.Compose(compositionBatch);

            foreach (var service in host.Services)
            {
                Console.WriteLine(service.InstanceId);
            }
        }
    }

    public class ServiceHost
    {
        [ImportMany]
        public IService[] Services { get; set; }
    }

    [Export(typeof(IService))]
    public class TestService : IService
    {
        public TestService()
        {
            this.InstanceId = ++Program.counter;
        }

        public int InstanceId { get; private set; }
    }
}

谢谢..伯尼

所以它按预期工作。 它找到 2 个实例,因为您添加了两个实例(一个手动添加,一个来自 DirectoryCatalog)。

您必须做出决定:让 MEF 管理您的实例,还是自己做。

如果可能,请删除[Export(typeof(IService))]并使用AddExportedValue而不是部分,如下所示:

// create an existing instance
TestService c = new TestService();
compositionBatch.AddExportedValue<IService>(c);

在这种情况下,您手动将您的实例添加到 compositionBatch,而 DirectoryCatalog 找不到它,原因是 class 没有[Exported]属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM