5

下面的代码在使用时不起作用RegistrationBuilder。当RegistrationBuilder未添加到 AssemblyCatalog 构造函数时,类型约束泛型起作用。

[TestClass]
public class TypeConstraints
{
    [TestMethod]
    public void TypeConstraintTest()
    {
        var rb = new RegistrationBuilder();
        var a = new AssemblyCatalog(Assembly.GetExecutingAssembly(), rb);
        //var a = new AssemblyCatalog(Assembly.GetExecutingAssembly()); //Works!
        var aggr = new AggregateCatalog(a);
        var c = new CompositionContainer(aggr);
        var item = c.GetExportedValue<IConstrained<Item>>();
        Assert.IsNotNull(item);
    }
}

public interface IConstrained<T> where T : IItem
{}

[Export(typeof (IConstrained<>))]
public class Constrained<T> : IConstrained<T> where T : IItem
{}

public class Item : IItem
{}

public interface IItem
{}
4

2 回答 2

3

首先,让我们描述一下究竟是什么导致了这种行为。

RegistrationBuilder 将程序集的实际类型包装在称为 CustomType 的代理类型中。这个代理或多或少只是为了让 RegistrationBuilder 有机会即时注入 Export 和 Import 属性。

遗憾的是,当您调用 GetGenericParameterConstraints 时,此代理也会返回包装类型。所以它不是一个 RuntimType IItem 你得到它是一个 CustomType IItem。当您尝试获取 IConstrained 的导出时,AssemblyCatalog 会检查很多内容以判断您的导出是否与您的导入匹配。其中一项检查是是否满足泛型类型约束。这或多或少是这样的支票。(简化)

exportToCheck.GenericTypeConstraints[0].IsAssignableFrom(typeof(Item))

CustomType 的 IsAssignableForm 方法是这样实现的。

public override bool IsAssignableFrom(Type c)
{
    ProjectingType projectingType = c as ProjectingType;
    return !(projectingType == null) && this.Projector == projectingType.Projector && 
              base.UnderlyingType.IsAssignableFrom(projectingType.UnderlyingType);
}

它仅在您传递另一种代理类型时才有效。

我真的认为这是 RegistrationBuilder 的一个主要错误,您应该将其报告给 Microsoft Connect。

要解决此问题,您必须取消投影与 ComposablePartDefinition 一起保存的 GenericTypeContraints。

坏消息是所有相关类都是内部的,因此您不能只覆盖 GetGenericParameterConstraints 方法。

我通过继承 AssemblyCatalog 并手动取消投影约束类型解决了这个问题。

公共类 MyAssemblyCatalog:AssemblyCatalog { private Func unprojectDelegate;

private bool projectionsChecked = false;

public MyAssemblyCatalog(Assembly assembly, CustomReflectionContext reflectionContext)
    : base(assembly, reflectionContext)
{
    this.ReflectionContext = reflectionContext;
}

public CustomReflectionContext ReflectionContext { get; private set; }

public Type Unproject(Type type)
{
    if (this.unprojectDelegate == null) {
        var param = Expression.Parameter(typeof(CustomReflectionContext));
        var param2 = Expression.Parameter(typeof(Type));
        var prop = Expression.Property(param, param.Type.GetProperty("Projector", BindingFlags.Instance | BindingFlags.NonPublic));
        var method = prop.Type.GetMethod("Unproject", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(Type) }, null);
        var body = Expression.Call(prop, method, param2);
        this.unprojectDelegate = Expression.Lambda<Func<CustomReflectionContext, Type, Type>>(body, param, param2).Compile();
    }
    return unprojectDelegate(this.ReflectionContext, type);
}

private void EnsureUnprojectedGenericTypeConstraints()
{
    if (!this.projectionsChecked) {
        foreach (var item in this) {
            object value1;
            if (item.Metadata.TryGetValue("System.ComponentModel.Composition.GenericParameterConstraints", out value1)) {
                var items = (object[])value1;
                foreach (var entry in items) {
                    var types = entry as Type[];
                    if (types != null) {
                        for (int i = 0; i < types.Length; i++) {
                            types[i] = Unproject(types[i]);
                        }
                    }
                }
            }
        }
        projectionsChecked = true;
    }
}

public override System.Collections.Generic.IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
{
    EnsureUnprojectedGenericTypeConstraints();
    return base.GetExports(definition);
}

}

现在测试有效。

[TestMethod]
public void TypeConstraintTest()
{
    var rb = new RegistrationBuilder();

    var a = new MyAssemblyCatalog(Assembly.GetExecutingAssembly(), rb);

    var aggr = new AggregateCatalog(a);
    var c = new CompositionContainer(aggr);
    var item = c.GetExportedValue<IConstrained<Item>>();

    Assert.IsNotNull(item);
}
于 2014-07-09T09:53:08.417 回答
0

更简单的解决方案:

/// <summary>
/// When RegistrationBuilder is used, there is problem with Generics constraints - in produced ExportDefinition is generics constraint with descriptior CustomType which is not comparable with Type. 
/// * so composition failed on Export not found exception.
/// http://stackoverflow.com/questions/24590096/type-constrained-open-generics-do-not-work-with-registrationbuilder
/// </summary>
public static class PatchCatalogForRegistrationBuilderBug
{
    public static void FixCatalogForRegistrationBuilderBug(this ComposablePartCatalog catalog)
    {
        foreach (var item in catalog)
        {
            object value1;
            if (item.Metadata.TryGetValue("System.ComponentModel.Composition.GenericParameterConstraints", out value1))
            {
                var items = (object[])value1;
                foreach (var entry in items)
                {
                    var types = entry as Type[];
                    if (types != null)
                    {
                        for (int i = 0; i < types.Length; i++)
                        {
                            if (((object)types[i]).GetType().FullName != "System.Reflection.Context.Custom.CustomType") continue; //cast to object is only for due to R# warning
                            types[i] = types[i].UnderlyingSystemType;
                        }
                    }
                }
            }
        }
    }
}
于 2017-04-20T07:27:51.923 回答