1

我已经为这个问题苦苦挣扎了几天,但我仍然不知道如何解决它。

我为 Unity Container 创建了一个容器扩展,使我能够轻松地在容器中注册装饰器类。这是我目前拥有的实现,与本文中的实现几乎相同

public class DecoratorExtension : UnityContainerExtension
{
    private int m_order;
    private Dictionary<Type, IList<DecoratorRegistration>> m_typeStacks;

    protected override void Initialize()
    {
        m_typeStacks = new Dictionary<Type, IList<DecoratorRegistration>>();
        Context.Registering += AddRegistration;
        Context.Strategies.Add(new DecoratorBuildStrategy(m_typeStacks), UnityBuildStage.PreCreation);
    }

    private void AddRegistration(object _sender, RegisterEventArgs _e)
    {
        if (_e.TypeFrom == null || !_e.TypeFrom.IsInterface)
            return;

        GetStack(_e.TypeFrom)
            .Add(new DecoratorRegistration {Order = m_order++, Type = _e.TypeTo});
    }

    private IList<DecoratorRegistration> GetStack(Type _type)
    {
        if (!m_typeStacks.ContainsKey(_type))
            m_typeStacks.Add(_type, new List<DecoratorRegistration>());

        return m_typeStacks[_type];
    }
}

这样做是为每种类型使用一个列表,以存储同一目标类型的所有类型注册,以便在调用 Resolve 时使用此构建策略重新组装它:

internal class DecoratorBuildStrategy : BuilderStrategy
{
    private readonly Dictionary<Type, IList<DecoratorRegistration>> m_typeStacks;

    internal DecoratorBuildStrategy(Dictionary<Type, IList<DecoratorRegistration>> _typeStacks)
    {
        m_typeStacks = _typeStacks;
    }

    public override void PreBuildUp(IBuilderContext _context)
    {
        var key = _context.OriginalBuildKey;
        if (_context.GetOverriddenResolver(key.Type) != null)
            return;

        // Only interfaces can use decorators.
        if (!key.Type.IsInterface)
            return;
        
        // Gets the list of types required to build the 'decorated' instance.
        // The list is reversed so that the least dependent types are built first.
        var decoratorTypes = GetDecoratorTypes(key.Type).Reverse().ToList();
        if (!decoratorTypes.Any())
            return;

        object value = null;
        foreach (var type in decoratorTypes)
        {
            Type typeToBuild = type;
            if (typeToBuild.IsGenericTypeDefinition)
            {
                Type[] genericArgumentTypes = key.Type.GetGenericArguments();
                typeToBuild = typeToBuild.MakeGenericType(genericArgumentTypes);
            }

            value = _context.NewBuildUp(new NamedTypeBuildKey(typeToBuild, key.Name));

            // An Override is created so that in the next BuildUp the already 
            // built object gets used instead of doing the BuildUp again and 
            // entering an infinite loop
            _context.AddResolverOverrides(new DependencyOverride(key.Type, value));
        }

        _context.Existing = value;
        _context.BuildComplete = true;
    }

    private IEnumerable<Type> GetDecoratorTypes(Type _type)
    {
        var typeList = m_typeStacks.GetValueOrDefault(_type) ?? new List<DecoratorRegistration>(0);
        if (!_type.IsGenericType)
            return typeList.Select(_reg => _reg.Type);

        // If the type is a generic type, we need to get all open generic registrations
        // alongside the closed ones
        var openGenericList = m_typeStacks
                .GetValueOrDefault(_type.GetGenericTypeDefinition()) ?? 
                new List<DecoratorRegistration>(0);

        // The final result is an ordered concatenation of the closed and open registrations 
        // that should be used for the type
        return typeList
            .Concat(openGenericList)
            .OrderBy(_registration => _registration.Order)
            .Select(_reg => _reg.Type);
    }
}

这就是使用 DecoratorRegistration 模型的地方。它只是一对表示注册顺序的 type/int。我创建它是为了能够正确混合打开和关闭的通用注册:

internal struct DecoratorRegistration
{
    public int Order { get; set; }
    public Type Type { get; set; }
}

这在很大程度上创造了奇迹。当我有一个实现两个接口的类时,问题就开始了,一个是装饰的,一个不是。

这是我正在尝试进行的当前测试用例:

private interface IAny<T> {}
private interface IAnotherInterface {}
private class Base<T> : IAnotherInterface, IAny<T> {}   
private class Decorator1<T> : IAny<T>
{
    internal readonly IAny<T> Decorated;

    public Decorator1(IAny<T> _decorated)
    {
        Decorated = _decorated;
    }
}

[TestMethod]
public void DecoratorExtensionDoesNotInterfereWithNormalRegistrations()
{
    // Arrange
    var container = new UnityContainer()
        .AddNewExtension<DecoratorExtension>()
        .RegisterType<Base<string>>(new ContainerControlledLifetimeManager())
        .RegisterType<IAny<string>, Decorator1<string>>()
        .RegisterType<IAny<string>, Base<string>>()
        .RegisterType<IAnotherInterface, Base<string>>();

    // Act
    var decorated = container.Resolve<IAny<string>>();
    var normal = container.Resolve<IAnotherInterface>();
    var anotherDecorated = container.Resolve<IAny<string>>();
    var anotherNormal = container.Resolve<IAnotherInterface>();

    // Assert
    Assert.IsInstanceOfType(normal, typeof (IAnotherInterface));
    Assert.IsInstanceOfType(decorated, typeof (Decorator1<string>));
    Assert.AreSame(normal, anotherNormal);
    Assert.AreSame(decorated, anotherDecorated);
}

这个测试应该让我的意图清楚。我想要单例类,但是对 Resolve 的第一次调用,IAnotherInterface或者IAny<string>导致每个后续调用都返回相同的东西。因此,我得到一个例外:

System.InvalidCastException: Unable to cast object of type 'Decorator1`1[System.String]' to type 'IAnotherInterface'.

在这条线上:

    var normal = container.Resolve<IAnotherInterface>();

我不确定在这里做什么。我不得不在我们的项目中暂时禁用单例,以便它可以按预期工作。我想要的是该Base<string>实例是一个单例,但是当我请求它时IAny<string>,它会创建一个新的实例,其中 SAME 基被装饰。

这仍然使用.Net 4.0,所以我在这里坚持使用Unity 2.1(不过在这种情况下应该没关系)。

4

2 回答 2

2

我已经有一段时间没有解决这个问题了,所以我认为最好复制我从 EntLib 团队的 Randy Levy 那里得到的答案。

它基本上归结为我用来注册装饰器实例的构建密钥。在我的代码中,实例实际上是使用基类类型注册的,而我需要使用实际的装饰器类型来注册它。

这篇文章有针对该问题的建议解决方法,这对我们来说非常有效。

于 2013-08-23T23:08:18.517 回答
1

我不确定这是否是您正在寻找的东西,但我认为这在您的测试中的特定情况下可以解决问题:

container.RegisterType<IAny<string>, Base<string>>(
    new ContainerControlledLifetimeManager(), "Inner");

container.RegisterType<IAny<string>, Decorator1<string>>(
    new InjectionConstructor(
        new ResolvedParameter(typeof(IAny<string>), "Inner")));

container.Register<IAnotherInterface>(new InjectionFactory(
    c => c.Resolve<IAny<string>>("Inner")));

你不需要那个扩展。

于 2013-07-05T14:00:28.443 回答