【问题标题】:MEF Add module twice to catalogMEF 将模块两次添加到目录
【发布时间】:2013-06-13 12:51:48
【问题描述】:

您知道如何将同一模块两次添加到具有不同参数的目录中吗?

ITest acc1 = new smalltest("a", 0)
ITest acc2 = new smalltest("b", 1)

AggregateCatalog.Catalogs.Add(??)
AggregateCatalog.Catalogs.Add(??)

提前致谢!

【问题讨论】:

    标签: module mef catalog


    【解决方案1】:

    由于 MEF 仅限于属性的使用,并且可以使用 Import 和 Export 属性进行配置,这与 IoC 容器通常提供的灵活性不同,因此可以在 MEF 中扩展 Part,可以从引用的 DLL,您还可以通过创建一个使用 [ExportAttribute] 公开一些属性的类来执行类似的操作,即类从先前的 MEF 部件继承。属性不仅限于在类上的使用,还可以应用于属性。例如,这样的事情怎么样。

    public class PartsToExport
    {
        [Export(typeof(ITest))]
        public Implementation A
        {
            get { return new Implementation("A", 5); }
        }
    
        [Export(typeof(ITest))]
        public Implementation B
        {
            get { return new Implementation("B", 10); }
        }
    }
    
    public interface ITest
    {
        void WhoAmI(Action<string, int> action);
    }
    
    [Export]
    public class Implementation : ITest
    {
        private string _method;
        private readonly int _value;
    
        public Implementation(string method, int value)
        {
            _method = method;
            _value = value;
        }
    
        public void WhoAmI(Action<string, int> action)
        {
            action(_method, _value);
        }
    }
    
    [TestClass]
    public class Tests
    {
        [TestMethod]
        public void Test()
        {
            var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
            CompositionContainer container = new CompositionContainer(catalog);
    
            var tests = container.GetExportedValues<ITest>();
    
            foreach (var test in tests)
            {
                test.WhoAmI((s, i) => Console.WriteLine("I am {0} with a value of {1}.", s, i));
            }
        }
    }
    

    这会将以下内容输出到控制台:

    我是 A,值为 5。
    我是 B,值为 10。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 2015-08-17
      相关资源
      最近更新 更多