使用Unity拦截对IMyInterface.SomeMethod的所有调用

时间:2012-08-10 20:56:15

标签: c# .net unity-container unity-interception

我正在努力学习Unity Interceptors,我正在努力学习它。

说我有这样的界面:

public interface IMyInterface
{
   void SomeMethod();
}

我有一些未知数量的类实现了这样的接口:

public class SpecificClass1 : IMyInterface
{
   public void SomeMethod()
   {
       Console.WriteLine("Method Called");
   }
}

我正在寻找一种说法,“对于IMyInterface的所有实例(我不想枚举它们),当调用SomeMethod时运行我的拦截器。

正在给我带来麻烦的classe的非枚举。 (如果你能枚举所有的课程,有很多例子。)

我已阅读类型拦截,但我似乎无法确定它是否能满足我的要求。

那里的任何Unity专家都知道如何做我想要的事情吗?

3 个答案:

答案 0 :(得分:18)

您可以创建InterceptionBehavior,然后在特定课程上注册。请注意,您可以在InvokeIMethodInvocation input

中过滤执行方法
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using NUnit.Framework;

namespace UnitTests
{
    [TestFixture]
    public class ForTest
    {
        [Test]
        public void Test()
        {
            IUnityContainer container = new UnityContainer().AddNewExtension<Interception>();
            container.RegisterType<IMyInterface, SpecificClass1>(
                new Interceptor<InterfaceInterceptor>(),
                new InterceptionBehavior<MyInterceptionBehavior>());
            var myInterface = container.Resolve<IMyInterface>();
            myInterface.SomeMethod();
        }
    }

    public interface IMyInterface
    {
        void SomeMethod();
    }

    public class SpecificClass1 : IMyInterface
    {
        #region IMyInterface

        public void SomeMethod()
        {
            Console.WriteLine("Method Called");
        }

        #endregion
    }

    public class MyInterceptionBehavior : IInterceptionBehavior
    {
        public bool WillExecute
        {
            get { return true; }
        }

        #region IInterceptionBehavior

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Enumerable.Empty<Type>();
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn result = getNext()(input, getNext);
            Console.WriteLine("Interception Called");
            return result;
        }

        #endregion
    }
}

控制台输出

Method Called
Interception Called

有关Interception with Unity

的更多信息

答案 1 :(得分:9)

@GSerjo概述了Unity拦截方法,该方法运行良好。如果您想自动执行拦截配置,可以使用UnityContainerExtension自动连接所有界面拦截以及行为。如果您想进行更具体的拦截(方法名称,签名,返回值等),那么您可能需要查看策略注入(使用与CallHandler匹配的规则)。

因此,在这种情况下,容器扩展名将如下所示:

public class UnityInterfaceInterceptionRegisterer : UnityContainerExtension
{
    private List<Type> interfaces = new List<Type>();
    private List<IInterceptionBehavior> behaviors = 
        new List<IInterceptionBehavior>();

    public UnityInterfaceInterceptionRegisterer(Type interfaceType, 
        IInterceptionBehavior interceptionBehavior)
    {
        interfaces.Add(interfaceType);
        behaviors.Add(interceptionBehavior);
    }

    public UnityInterfaceInterceptionRegisterer(Type[] interfaces, 
        IInterceptionBehavior[] interceptionBehaviors)
    {            
        this.interfaces.AddRange(interfaces);
        this.behaviors.AddRange(interceptionBehaviors);

        ValidateInterfaces(this.interfaces);
    }

    protected override void Initialize()
    {
        base.Container.AddNewExtension<Interception>();

        base.Context.Registering += 
            new EventHandler<RegisterEventArgs>(this.OnRegister);
    }

    private void ValidateInterfaces(List<Type> interfaces)
    {
        interfaces.ForEach((i) =>
        {
            if (!i.IsInterface)
                throw new ArgumentException("Only interface types may be configured for interface interceptors");
        }
        );
    }

    private bool ShouldIntercept(RegisterEventArgs e)
    {
        return e != null && e.TypeFrom != null && 
               e.TypeFrom.IsInterface && interfaces.Contains(e.TypeFrom);
    }

    private void OnRegister(object sender, RegisterEventArgs e)
    {
        if (ShouldIntercept(e))
        {
            IUnityContainer container = sender as IUnityContainer;

            var i = new Interceptor<InterfaceInterceptor>();
            i.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, Context.Policies);

            behaviors.ForEach( (b) =>
                {
                    var ib = new InterceptionBehavior(b);
                    ib.AddPolicies(e.TypeFrom, e.TypeTo, e.Name, Context.Policies);
                }
            );
        }
    }
}

然后你可以像这样使用它:

IUnityContainer container = new UnityContainer()
    .AddExtension(new UnityInterfaceInterceptionRegisterer(
        new Type[] { typeof(IMyInterface), 
                     typeof(IMyOtherInterface) }, 
        new IInterceptionBehavior[] { new MyInterceptionBehavior(), 
                                      new AnotherInterceptionBehavior() }
        ));

container.RegisterType<IMyInterface, SpecificClass1>();

var myInterface = container.Resolve<IMyInterface>();
myInterface.SomeMethod();

现在,当注册接口时,相应的拦截策略也将添加到容器中。因此,在这种情况下,如果注册的接口是IMyInterface或IMyOtherInterface类型,则将设置策略以进行接口拦截,并且还将添加拦截行为MyInterceptionBehavior和AnotherInterceptionBehavior。

请注意,Unity 3(在此问题/答案之后发布)添加了Registration by Convention功能,可以执行此扩展程序的功能(无需编写任何自定义代码)。 Developer's Guide to Dependency Injection Using Unity

中的一个示例
var container = new UnityContainer();

container.AddNewExtension<Interception>();
container.RegisterTypes(
    AllClasses.FromLoadedAssemblies().Where(
      t => t.Namespace == "OtherUnitySamples"),
    WithMappings.MatchingInterface,
    getInjectionMembers: t => new InjectionMember[]
    {
      new Interceptor<VirtualMethodInterceptor>(),
      new InterceptionBehavior<LoggingInterceptionBehavior>()
    });

答案 2 :(得分:0)

设置拦截需要多个动作,包括。拦截类型,策略和处理程序的配置。

首先查看Using Interception in Applications,了解支持拦截的情况类型的一般细节(例如,有或没有DI容器)。然后,请参阅Type Interception以获取有关受支持的类型拦截器的更多详细信息。特别要注意哪些拦截器可以与你的类的类型一起使用(否则处理程序永远不会触发)。

当你决定使用什么拦截器时,配置它并根据上面的链接创建一个足够的调用处理程序。如果此时仍有问题,请发布更详细的问题。如果您已经这样做了,请将配置和代码发布为“非枚举的classe”,只是没有给出任何提示您实际要求的内容。您是否有任何机会意味着“枚举”您指定了属性驱动的策略,并且没有它就无法实现您想要的目标?

相关问题