mef2 SatisfyImportsOnce不能处理派生类型

本文关键字:派生 类型 处理 不能 SatisfyImportsOnce mef2 | 更新日期: 2023-09-27 18:14:43

我正在努力理解为什么当我用接口的实现者而不是接口本身替换ImportProperty行时,我的代码正在工作:

[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 => flyweight. abstractions)

可以,但是:

registrationBuilder.ForTypesDerivedFrom>>()。ImportProperty(flyweight => flyweight. abstractions)

没有,尽管我认为它们在我的例子中应该是相等的。

mef2 SatisfyImportsOnce不能处理派生类型

我意识到"import"只适用于类,而不适用于接口。

一个解决方案是导入所有的属性:

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

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