用于多个接口的装饰器 - Autofac中的循环依赖性谜语

时间:2017-02-16 16:28:34

标签: c# dependency-injection decorator autofac circular-dependency

我来自Ninject,但我决定尝试Autofac,因为它似乎更积极地开发。到目前为止,我可以说使用.WhenInjectedExactlyInto语法注册装饰器并不像在Ninject中那么容易。无论如何,请耐心等待我,因为我是一个Autofac新手。

问题在于:

我的A类型实现了由IA修饰的接口A_DecoratorA_Decorator实现接口IAIB,然后应由AB_Decorator修饰,同时实现IAIBAB_Decorator采用类型IAIB的两个依赖项(因此它是两者的装饰器)但它们都应该解析为A_Decorator的同一个实例。它看起来像这样:AB_Decorator(A_Decorator(A) as IA, A_Decorator(A) as IB)。从Autofac容器请求类型IA或类型IB的服务时,它们应引用单个AB_Decorator实例。

通过单词描述有点棘手,但这是我能想出的最简单的代码示例,它显示了这种情况(我已经向构造函数添加了实例ID和跟踪消息以查看发生了什么):

using System;
using Autofac;

namespace AutofacExample
{
    internal interface IA { }

    internal interface IB { }

    class A : IA
    {
        static int _instanceCounter;
        readonly int Id = ++_instanceCounter;

        public A()
        {
            Console.WriteLine(this);
        }

        public override string ToString()
        {
            return $"{GetType().Name}[{nameof(Id)}={Id}]";
        }
    }

    class A_Decorator : IA, IB
    {
        static int _instanceCounter = 10;
        readonly int Id = ++_instanceCounter;

        /* decorated1 should reference instance of A */

        public A_Decorator(IA decoratedA)
        {
            Console.WriteLine($"{this}({nameof(decoratedA)}={decoratedA})");
        }

        public override string ToString()
        {
            return $"{GetType().Name}[{nameof(Id)}={Id}]";
        }
    }

    class AB_Decorator : IA, IB
    {
        static int _instanceCounter = 100;
        readonly int Id = ++_instanceCounter;

        /* Both decorated1 and decorated2 should reference the same instance of A_Decorator */

        public AB_Decorator(IA decoratedA, IB decoratedB)
        {
            Console.WriteLine($"{this}({nameof(decoratedA)}={decoratedA}, {nameof(decoratedB)}={decoratedB})");
        }

        public override string ToString()
        {
            return $"{GetType().Name}[{nameof(Id)}={Id}]";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ContainerBuilder builder = new ContainerBuilder();

            builder
                .RegisterType<A>()
                .Named<IA>(nameof(A))
                .SingleInstance();

            builder
                .RegisterType<A_Decorator>()
                .Named<IA>(nameof(A_Decorator))
                .Named<IB>(nameof(A_Decorator))
                .SingleInstance();

            builder
                .RegisterType<AB_Decorator>()
                .Named<IA>(nameof(AB_Decorator))
                .Named<IB>(nameof(AB_Decorator))
                .SingleInstance();

            /* A is decorated by A_Decorator as IA */
            builder
                .RegisterDecorator<IA>(
                    (c, decorated) =>
                        c.ResolveNamed<IA>(nameof(A_Decorator), TypedParameter.From(decorated)),
                    nameof(A))
                //.Keyed<IA>("innerA")
                //.Keyed<IB>("innerB")
                .SingleInstance();

            /* Trying to register AB_Decorator as IA creates circular dependency */
            //builder
            //    .RegisterDecorator<IA>(
            //        (c, decorated) =>
            //            c.ResolveNamed<IA>(nameof(AB_Decorator), TypedParameter.From(decorated)),
            //        "innerA")
            //    .SingleInstance();

            /* A_Decorator is decorated by AB_Decorator as IB */
            builder
                .RegisterDecorator<IB>(
                        (c, decorated) =>
                            c.ResolveNamed<IB>(nameof(AB_Decorator), TypedParameter.From(decorated)),
                        nameof(A_Decorator) /* "innerB" */)
                    .SingleInstance();

            IContainer container = builder.Build();

            IA a = container.Resolve<IA>();
            IB b = container.Resolve<IB>();

            Console.WriteLine($"{nameof(a)} == {nameof(b)} ? {ReferenceEquals(a, b)}");
            Console.WriteLine($"{nameof(a)} is {a.GetType().Name}");
            Console.WriteLine($"{nameof(b)} is {b.GetType().Name}");
        }
    }
}

不幸的是,请求IA的实例给了我A_Decorator,而对于IB,我获得了AB_Decorator。试图取消注释额外的装饰器注册块会导致循环依赖异常(DependencyResolutionException: Circular component dependency detected: System.Object -> AutofacExample.AB_Decorator -> System.Object -> AutofacExample.AB_Decorator),并且我无法尝试尝试命名注册的各种组合。

有谁知道这个解决方案?提前谢谢。

2 个答案:

答案 0 :(得分:2)

问题

问题在于AB_Decorator的装饰者注册。特别是lambda函数解析AB_Decorator

( c, decorated ) => c.ResolveNamed<IA>( nameof( AB_Decorator ), TypedParameter.From( decorated ) );

AB_Decorator的构造函数接受2个参数,这两个参数都应该是A_Decorator的同一个实例,它作为decorated提供给lambda。但是,decorated仅作为参数通过TypedParameter.From( decorated )传递一次。因此,Autofac将尝试通过容器解析第二个参数。

现在IB的注册表明我们应该在A_Decorator中包含AB_Decorator的单例实例。因此,要解析IB,容器必须构建AB_Decorator。出现问题,我们目前正在尝试将AB_Decorator解析为IA,但我们需要IB来完成AB_Decorator的构造函数参数正在为IA建造。并且IB在容器中注册为AB_Decorator。所以你得到:

AB_Decorator(A_Decorator(A) as IA, AB_Decorator(A_Decorator(A) as IA, AB_Decorator(etc...))

解决方案

我们需要在解析decorated时将AB_Decorator传递给两个参数。像这样:

builder
    .RegisterDecorator<IA>(
        ( c, decorated ) =>

            c.ResolveNamed<IA>( nameof( AB_Decorator ),
                new TypedParameter( typeof( IA ), decorated ),
                new TypedParameter( typeof( IB ), decorated )
            )
        ,"innerA"
    )
    .SingleInstance();


builder
    .RegisterDecorator<IB>(
        ( c, decorated ) =>

            c.ResolveNamed<IB>( nameof( AB_Decorator ),
                new TypedParameter( typeof( IA ), decorated ),
                new TypedParameter( typeof( IB ), decorated )
            )
        , nameof( A_Decorator ) /* "innerB" */
    )
    .SingleInstance();

现在我们向decoratedA_Decorator参数发送IA IB TypedParameter。直接构造AB_Decorator实例允许我在参数列表中指定我希望实例实现的类型,在本例中为$rows = mysqli_query($connection, "SELECT * FROM clienti_orhideea WHERE data_inregistrare between STR_TO_DATE('$begin', '%d-%m-%Y') AND STR_TO_DATE('$end', '%d-%m-%Y') ORDER BY data_inregistrare ASC" );

答案 1 :(得分:1)

你走了:

ContainerBuilder builder = new ContainerBuilder();

builder
    .RegisterType<A>()
    .Named<IA>(nameof(A))
    .SingleInstance();

builder
    .RegisterType<A_Decorator>()
    .Named<IA>(nameof(A_Decorator))
    .Named<IB>(nameof(A_Decorator))
    .WithParameter(new ResolvedParameter((pi, c) => pi.Name == "decoratedA", 
        (pi, c) => c.ResolveNamed<IA>(nameof(A))))
    .SingleInstance();

builder
    .RegisterType<AB_Decorator>()
    .As<IA, IB>()
    .WithParameter(new ResolvedParameter((pi, c) => pi.Name == "decoratedA",
        (pi, c) => c.ResolveNamed<IA>(nameof(A_Decorator))))
    .WithParameter(new ResolvedParameter((pi, c) => pi.Name == "decoratedB",
        (pi, c) => c.ResolveNamed<IB>(nameof(A_Decorator))))
    .SingleInstance();

IContainer container = builder.Build();

打印:

A[Id=1]
A_Decorator[Id=11](decoratedA=A[Id=1])
AB_Decorator[Id=101](decoratedA=A_Decorator[Id=11], decoratedB=A_Decorator[Id=11])
a == b ? True
a is AB_Decorator
b is AB_Decorator

API令人困惑,因为在这种情况下你不需要RegisterDecorator()(它可以同时装饰一整套组件)。

(如果我们能烘焙整个食物会很好:

    .WithParameter(new ResolvedParameter((pi, c) => pi.Name == "decoratedA", 
        (pi, c) => c.ResolveNamed<IA>(nameof(A))))

在Autofac中成为一个更简单的WithParameter()重载;如果你在这里看到胜利,我认为这是一个很好的建议来加强项目的问题跟踪器。)