Unity拦截配置-如何减少冗长?

问题描述

| 要在Unity 2.0中设置侦听功能,请在您的配置中添加以下内容(取自Unity文档)...
      <policy name=\"addDataAccessTypes\">
        <matchingRule name=\"DataLayerMatch\" type=\"NamespaceMatchingRule\">
          <constructor>
            <param name=\"namespaceName\" value=\"MyApp.DataAccess\" />
          </constructor>
        </matchingRule>
        <callHandler name=\"LogHandler\" type=\"LoggingCallHandler\" />
        <callHandler name=\"SecurityHandler\"
            type=\"DatabaseSecurityCheckHandler\" />
      </policy>
是否可以使用相同的处理类为侦听设置多个接口? 例如。像这样的东西
<constructor>
    < interface to intercept 1 />
    < interface to intercept 2 />
</construtor>
使用unity示例中给出的方法,如果您要拦截的接口很多,则配置文件将变得非常冗长。     

解决方法

如果使用
Unity.Interception
程序集,则可以更流畅地进行属性拦截。缺点是被拦截的类确实(以某种方式)知道该方面: 一个非常快速的设置示例如下所示:
class Program
{
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine();
            Console.WriteLine(\"Starting test...\");

            var container = new UnityContainer();
            container.AddNewExtension<Interception>();
            container.Configure<Interception>()
                .SetDefaultInterceptorFor<IGadget>(new InterfaceInterceptor());

            container.RegisterType<IGadget,Gadget>();

            var gadget = container.Resolve<IGadget>();
            gadget.DoSomething();
        }
        catch (Exception ex)
        {
            Console.WriteLine();
            Console.WriteLine(\"An error has occurred: {0}\",ex);
        }
        finally
        {
            Console.WriteLine();
            Console.WriteLine(\"Test complete.\");
            Console.ReadKey();
        }
    }
}



public class LogAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(IUnityContainer container)
    {
        return container.Resolve<LogHandler>();
    }
}

public class LogHandler : ICallHandler
{
    public int Order { get; set; }

    public IMethodReturn Invoke(IMethodInvocation input,GetNextHandlerDelegate getNext)
    {
        Console.WriteLine(\"*** Logging the action! -{0}-\",input.MethodBase.Name);
        return getNext()(input,getNext);
    }
}

public interface IGadget
{
    void DoSomething();
}

[Log]
public class Gadget : IGadget
{
    public void DoSomething()
    {
        Console.WriteLine(\"\\tI did something!\");
    }
}
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...