拦截给定程序集的所有方法

时间:2018-03-05 07:57:15

标签: c# dependency-injection unity-container aop

我试图在调用消息之前和之后拦截匹配的所有方法并记录日志。以下代码无法解析实例!!!

我有一个IDemo接口,由Demo和Demo2类实现。 Unity在配置文件中配置。我只是调用LoadConfiguration方法来加载统一。当我调用container.Resolve()时,它没有解析类型。

请帮忙

代码文件

using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using Unity;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;

namespace AopDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var container = new UnityContainer();
                container.LoadConfiguration();
                var demo = container.Resolve<IDemo>();
                demo.DoSomething("123", 123);
            }
            catch (Exception ex) { Console.WriteLine(ex); }

            Console.ReadKey();
        }
    }

    public interface IDemo
    {
        void DoSomething(string message, int number);
    }

    public class Demo : IDemo
    {
        public Demo() { }

        public void DoSomething(string message, int number)
        {
            Console.WriteLine($"Demo - Doing Something !!! | message = {message}, number = {number}");
        }
    }

    public class AopInterceptionBehavior : IInterceptionBehavior
    {
        public bool WillExecute => true;
        public IEnumerable<Type> GetRequiredInterfaces() => Type.EmptyTypes;
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("Before Invoking the method");
            var result = getNext().Invoke(input, getNext);
            Console.WriteLine("After Invoking the method");
            return result;
        }
    }
}

配置文件

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration" />
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration" />
    <container>
      <extension type="Interception" />
      <register type="IMatchingRule" mapTo="NamespaceMatchingRule">
        <constructor>
          <param name="namespaceName" value="AopDemo.*" />
        </constructor>
        <interceptor type="InterfaceInterceptor"/>
        <interceptionBehavior type="AopDemo.AopInterceptionBehavior, AopDemo" />
      </register>
    </container>
  </unity>
</configuration>

错误消息:

enter image description here

0 个答案:

没有答案