Castle Windsor ArrayResolver пытается создать неразрешимую зависимость массива - PullRequest
4 голосов
/ 25 октября 2010

При использовании ArrayResolver, если я регистрирую несколько реализаций интерфейса и класса, который зависит от массива указанных интерфейсов, я ожидаю, что распознаватель массивов внедрит все реализации интерфейса, которые могут быть успешно разрешены. Если зарегистрированная реализация этого интерфейса не может быть разрешена, она не будет внедрена в зависимый класс (очевидно), и контейнер не вызовет исключение.

Начиная с Windsor 2.5.1, ArrayResolver будет генерировать исключение в этой ситуации, но только если класс, который он пытается создать, имеет несколько конструкторов.

Я не уверен, было ли это изменение в поведении преднамеренным или нет. Я не вижу в документе 2.5.1 критических изменений ничего такого, что могло бы заставить меня поверить, что это было сделано намеренно.

Пожалуйста, смотрите тестовый пример ниже:

using System;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.Windsor;
using NUnit.Framework;

namespace CastleTests
{
    [TestFixture]
    public class TestArrayResolver
    {
        /// <summary>
        /// In this test, we register two implementors of IDependency, and a "DependsOnArray" class
        /// that depends on an array of IDependency.  The "UnresolvalbeDependency" cannot be
        /// resolved (because its dependency on "IUnimplementedDependency" is not satisfied)
        /// Hence, only the "ResolvableDependency" is injected into "DependsOnArray"
        /// </summary> 
        [Test]
        public void ArrayResolution_UnresolvableDependencyIsNotIncluded()
        {
            using (var container = new WindsorContainer())
            {
                container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel, false));
                container.Register(
                    Component.For<IDependency>().ImplementedBy<ResolvableDependency>(),
                    Component.For<IDependency>().ImplementedBy<UnresolvalbeDependency>(),
                    Component.For<IDependOnArray>().ImplementedBy<DependsOnArray>()
                    );
                container.Resolve<IDependOnArray>();
            }
        }

        /// <summary>
        /// This test is identical to the above, except instead of registering "UnresolvableDependency"
        /// we register "UnresolvalbeDependencyWithPrimitiveConstructor", which is identical to
        /// "UnresolvableDependency", except for the fact that it has a second constructor acceptin a string.
        /// 
        /// I would expect this test to behave the same way as the above test, which it does in windsor 2.5,
        /// however in 2.5.1 and later, it fails with the following error message:
        /// 
        /// Castle.MicroKernel.ComponentActivator.ComponentActivatorException : Could not find resolvable constructor for CastleTests.UnresolvalbeDependencyWithAdditionalConstructor. Make sure all required dependencies are provided.
        /// </summary> 
        [Test]
        public void ArrayResolution_UnresolvableDependencyCausesResolutionFailure()
        {
            using (var container = new WindsorContainer())
            {
                container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel, true));
                container.Register(
                    Component.For<IDependency>().ImplementedBy<ResolvableDependency>(),
                    Component.For<IDependency>().ImplementedBy<UnresolvalbeDependencyWithPrimitiveConstructor>(),
                    Component.For<IDependOnArray>().ImplementedBy<DependsOnArray>()
                    );
                container.Resolve<IDependOnArray>();
            }
        }

        /// <summary>
        /// this test fails with the same error as the above test, indicating that the issue is not related to the
        /// primitive vs. service nature of the second cosntructor's parameter
        /// </summary>
        [Test]
        public void ArrayResolution_UnresolvableDependencyCausesResolutionFailure_ServiceConstructor()
        {
            using (var container = new WindsorContainer())
            {
                container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel, true));
                container.Register(
                    Component.For<IDependency>().ImplementedBy<ResolvableDependency>(),
                    Component.For<IDependency>().ImplementedBy<UnresolvalbeDependencyWithAdditionalServiceConstructor>(),
                    Component.For<IDependOnArray>().ImplementedBy<DependsOnArray>()
                    );
                container.Resolve<IDependOnArray>();
            }
        }
    }

    public interface IDependency
    {
    }

    public class ResolvableDependency : IDependency
    {
    }

    public interface IUnimplementedDependency
    {
    }

    public class UnresolvalbeDependency : IDependency
    {
        public UnresolvalbeDependency(IUnimplementedDependency unimplementedDependency)
        {
        }
    }

    public interface IOtherUnimplementedDependency
    {
    }

    public class UnresolvalbeDependencyWithAdditionalServiceConstructor : IDependency
    {
        public UnresolvalbeDependencyWithAdditionalServiceConstructor(IUnimplementedDependency unimplementedDependency)
        {
        }

        public UnresolvalbeDependencyWithAdditionalServiceConstructor(IOtherUnimplementedDependency dep)
        {
        }
    }

    public class UnresolvalbeDependencyWithPrimitiveConstructor : IDependency
    {
        public UnresolvalbeDependencyWithPrimitiveConstructor(IUnimplementedDependency unimplementedDependency)
        {
        }

        public UnresolvalbeDependencyWithPrimitiveConstructor(string str)
        {
        }
    }

    public interface IDependOnArray
    {
    }

    public class DependsOnArray : IDependOnArray
    {
        public DependsOnArray(params IDependency[] dependencies)
        {
            foreach (var dependency in dependencies)
            {
                Console.WriteLine(dependency.GetType().Name);
            }
        }
    }
}

Полная трассировка стека исключения приведена ниже:

at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.SelectEligibleConstructor(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\DefaultComponentActivator.cs: line 288
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\DefaultComponentActivator.cs: line 104
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\DefaultComponentActivator.cs: line 85
at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\AbstractComponentActivator.cs: line 75
at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Lifestyle\SingletonLifestyleManager.cs: line 50
at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Handlers\DefaultHandler.cs: line 61
at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context, Boolean instanceRequired) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Handlers\AbstractHandler.cs: line 770
at Castle.MicroKernel.Handlers.AbstractHandler.TryResolve(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Handlers\AbstractHandler.cs: line 376
at Castle.MicroKernel.DefaultKernel.TryResolveComponent(IHandler handler, Type service, IDictionary additionalArguments) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\DefaultKernel.cs: line 899
at Castle.MicroKernel.DefaultKernel.ResolveAll(Type service, IDictionary arguments) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\DefaultKernel_Resolve.cs: line 293
at Castle.MicroKernel.Resolvers.SpecializedResolvers.ArrayResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Resolvers\SpecializedResolvers\ArrayResolver.cs: line 71
at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Resolvers\DefaultDependencyResolver.cs: line 239
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArgumentsCore(ConstructorCandidate constructor, Object[] arguments, CreationContext context, Type[] signature) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\DefaultComponentActivator.cs: line 367
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context, Type[]& signature) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\DefaultComponentActivator.cs: line 344
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\DefaultComponentActivator.cs: line 107
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\DefaultComponentActivator.cs: line 85
at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\ComponentActivator\AbstractComponentActivator.cs: line 75
at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Lifestyle\SingletonLifestyleManager.cs: line 50
at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Handlers\DefaultHandler.cs: line 61
at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context, Boolean instanceRequired) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\Handlers\AbstractHandler.cs: line 770
at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\MicroKernel\DefaultKernel.cs: line 880
at Castle.Windsor.WindsorContainer.Resolve(Type service) in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\Windsor\WindsorContainer.cs: line 889
at Castle.Windsor.WindsorContainer.Resolve() in c:\TeamCity\buildAgent\work\1ab5e0b25b145b19\src\Castle.Windsor\Windsor\WindsorContainer.cs: line 978
at CastleTests.TestArrayResolver.ArrayResolution_UnresolvableDependencyCausesResolutionFailure() in TestArrayResolver.cs: line 54 

Я подтвердил правильное (без исключений) поведение в 2.5 и подтвердил неправильное поведение в 2.5.1, а также сборки стволов 2146 и 2137.

1 Ответ

1 голос
/ 23 марта 2011

Теперь это исправлено, как указал Маурисио (добавив этот ответ, чтобы вопрос мог быть закрыт) * ​​1001 *

...