2015-09-26 76 views
0

我挣扎理解为什么我的代码工作只是当我与接口,而不是接口本身的实现者更换ImportProperty行:MEF 2 SatisfyImportsOnce不起作用的派生类型

[TestFixture] 
public class FlyweightTest 
{ 
    [MetadataAttribute] 
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] 
    class FlyweightIntegerKeyAttribute : ExportAttribute, IFlyweightKey<int> 
    { 
     public int Key { get; private set; } 

     public FlyweightIntegerKeyAttribute(int key) : base(typeof(IAbstraction)) { Key = key; } 
    } 

    public interface IAbstraction { } 

    [FlyweightIntegerKey(1)] 
    class Abstraction1 : IAbstraction { } 

    [FlyweightIntegerKey(2)] 
    class Abstraction2 : IAbstraction { } 

    [Test] 
    public void Test() 
    { 
     IMefFlyweight<IAbstraction, IFlyweightKey<int>> lFlyweight = new Flyweight(); 

     Initialize(lFlyweight); 

     Assert.AreEqual(2, lFlyweight.Abstractions.Count()); 
     Assert.IsTrue(lFlyweight.Abstractions.Select(lazy => lazy.Value).OfType<Abstraction1>().Any()); 
     Assert.IsTrue(lFlyweight.Abstractions.Select(lazy => lazy.Value).OfType<Abstraction2>().Any()); 
    } 

    //public interface IMefFlyweight<T, TMetadata> 
    //{ 
    // IEnumerable<Lazy<T, TMetadata>> Abstractions { get; set; } 
    //} 

    public class Flyweight : IMefFlyweight<IAbstraction, IFlyweightKey<int>> 
    { 
     public IEnumerable<Lazy<IAbstraction, IFlyweightKey<int>>> Abstractions { get; set; } 
    } 

    public void Initialize(IMefFlyweight<IAbstraction, IFlyweightKey<int>> @object) 
    { 
     var catalog = new AggregateCatalog(); 
     var registrationBuilder = new RegistrationBuilder(); 

     registrationBuilder.ForTypesDerivedFrom<IAbstraction>().Export<Lazy<IAbstraction, IFlyweightKey<int>>>(); 

     //registrationBuilder.ForTypesDerivedFrom<IMefFlyweight<IAbstraction, IFlyweightKey<int>>>().ImportProperty(flyweight => flyweight.Abstractions); 
     // This one works: 
     registrationBuilder.ForType<Flyweight>().ImportProperty(flyweight => flyweight.Abstractions); 

     foreach (var lAssembly in AppDomain.CurrentDomain.GetAssemblies()) 
      catalog.Catalogs.Add(new AssemblyCatalog(lAssembly, registrationBuilder)); 

     var container = new CompositionContainer(catalog); 

     container.SatisfyImportsOnce(@object, registrationBuilder); 
    } 

的:

registrationBuilder.ForType()ImportProperty(轻量级=> flyweight.Abstractions)

工作正常,但:

registrationBuilder.ForTypesDerivedFrom >>()。ImportProperty(轻量级=> flyweight.Abstractions)

没有,虽然我相信他们应该是在我的情况等同。

回答

0

我意识到“导入”只适用于类而不是界面。

的溶液可以导入所有属性:

registrationBuilder.ForTypesDerivedFrom<IImportingInterface>().ImportProperties(_ => true); 

registrationBuilder.ForTypesDerivedFrom<IImportingInterface>().ImportProperties<ExportClass>(_ => true);