การสกัดกั้นแอตทริบิวต์ระดับวิธีการด้วย Autofac

(นี่เป็นคำถามที่เกี่ยวข้องกับคำถามนี้ ซึ่งใช้สำหรับ SimpleInjector ฉันเป็น แนะนำให้สร้างคำถามแยกกันสำหรับแต่ละคอนเทนเนอร์ IoC)

ด้วย Unity ฉันสามารถเพิ่มการสกัดกั้นตามคุณลักษณะเช่นนี้ได้อย่างรวดเร็ว

public sealed class MyCacheAttribute : HandlerAttribute, ICallHandler
{
   public override ICallHandler CreateHandler(IUnityContainer container)
   {
        return this;
   }

   public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
   {
      // grab from cache if I have it, otherwise call the intended method call..
   }
}

จากนั้นฉันลงทะเบียนกับ Unity ด้วยวิธีนี้:

  container.RegisterType<IPlanRepository, PlanRepository>(new ContainerControlledLifetimeManager(),
           new Interceptor<VirtualMethodInterceptor>(),
           new InterceptionBehavior<PolicyInjectionBehavior>());

ในรหัสพื้นที่เก็บข้อมูลของฉัน ฉันสามารถเลือกตกแต่งวิธีการบางอย่างที่จะแคชได้ (ด้วยค่าแอตทริบิวต์ที่สามารถปรับแต่งแยกกันสำหรับแต่ละวิธี):

    [MyCache( Minutes = 5, CacheType = CacheType.Memory, Order = 100)]
    public virtual PlanInfo GetPlan(int id)
    {
        // call data store to get this plan;
    }

ฉันกำลังสำรวจวิธีการที่คล้ายกันใน Autofac จากสิ่งที่ฉันอ่านและค้นหาดูเหมือนว่ามีเพียงการสกัดกั้นระดับอินเทอร์เฟซ/ประเภทเท่านั้น แต่ฉันชอบตัวเลือกในการตกแต่งวิธีการแต่ละวิธีด้วยพฤติกรรมการสกัดกั้นที่ควบคุมคุณลักษณะประเภทนี้ มีคำแนะนำอะไรบ้าง?


person Calvin    schedule 10.03.2015    source แหล่งที่มา


คำตอบ (1)


คุณพูดถูกเมื่อคุณบอกว่าไม่มีการสกัดกั้นระดับวิธีการ อย่างไรก็ตาม เมื่อคุณใช้ write a type interceptor คุณจะสามารถเข้าถึงวิธีการที่ถูกเรียกใช้ได้ หมายเหตุ: ขึ้นอยู่กับแพ็คเกจ Autofac.Extras.DynamicProxy2

    public sealed class MyCacheAttribute : IInterceptor
    {

        public void Intercept(IInvocation invocation)
        {
            // grab from cache if I have it, otherwise call the intended method call..

            Console.WriteLine("Calling " + invocation.Method.Name);

            invocation.Proceed();
        }
    }

ทะเบียนก็จะประมาณนี้

     containerBuilder.RegisterType<PlanRepository>().As<IPlanRepository>().EnableInterfaceInterceptors();
     containerbuilder.RegisterType<MyCacheAttribute>();
person gaunacode.com    schedule 10.03.2015
comment
ดูเหมือนว่าทั้ง Autofac และ SimpleInjector กำลังใช้ Dynamic proxy และไม่มีการสนับสนุนนอกกรอบสำหรับการสกัดกั้นที่มีการระบุแหล่งที่มา Steven จัดเตรียมโซลูชันทั่วไปสำหรับการสกัดกั้นอินเทอร์เฟซที่นี่: stackoverflow.com/a/28969513/879655 - person Calvin; 11.03.2015
comment
@Calvin: เพื่อให้แม่นยำยิ่งขึ้น: Simple Injector ไม่รองรับการสกัดกั้นด้วยซ้ำ ไม่มีแพ็คเกจหรือส่วนขยายสำหรับทำการสกัดกั้น - person Steven; 12.03.2015