1. 程式人生 > 實用技巧 >控制檯應用程式使用Autofac實現AOP

控制檯應用程式使用Autofac實現AOP

1 安裝依賴包

安裝 Autofac 和 Autofac.Extras.DynamicProxy

2 定義攔截器類

using System;
using System.Linq;

using Castle.DynamicProxy; // 新增引用

namespace ConsoleApp_AutofacAop
{
    /// <summary>
    /// 攔截器需要實現 IInterceptor 介面
    /// </summary>
    public class LogInterceptor : IInterceptor
    {
        public
void Intercept(IInvocation invocation) { #region 方法執行前 string beforeExe_msg = string.Format("方法執行前:攔截[{0}]類下的方法[{1}]的引數是[{2}]", invocation.InvocationTarget.GetType(), invocation.Method.Name, string.Join(", ", invocation.Arguments.Select(a => (a ?? ""
).ToString()).ToArray())); Console.WriteLine(beforeExe_msg); #endregion #region 方法執行 invocation.Proceed(); #endregion #region 方法執行完成後 string afterExe_msg = string.Format("方法執行完畢,返回結果:{0}", invocation.ReturnValue); Console.WriteLine(afterExe_msg);
#endregion } } }

3 定義需要被攔截的類,在被攔截的類上加上 Intercept 特性

using System;
using System.Collections.Generic;
using System.Text;

using Autofac.Extras.DynamicProxy; // 新增引用


namespace ConsoleApp_AutofacAop
{
    /// <summary>
    /// 定義被攔截的類
    /// </summary>
    [Intercept(typeof(LogInterceptor))] // Person 使用 LogInterceptor攔截器
    public class Person
    {
        public int Age { get; set; }

        public Person(){}
        
        // 非虛方法不會被攔截到
        public void Method_NoVirtua()
        {
            Console.WriteLine("Method_NoVirtua");
        }

        public virtual void Method2()
        {
            Console.WriteLine("Method2");
        }

        public virtual string Method3(string para1,string para2)
        {
            Console.WriteLine("Method3");
            return para1 + "&" + para2;
        }
    }
}

被攔截類上的方法需要是virtual虛方法,不然不會被攔截到

4 初始化Aufofac容器,然後註冊攔截器和被攔截的類,並且在被攔截的類上啟用類攔截

        #region 在應用的啟動地方構造Autofac容器並註冊依賴
        // 定義容器
        private static IContainer Container { get; set; }

        /// <summary>
        /// 初始化Autofac
        /// </summary>
        private static void AutofacInit()
        {
            var builder = new ContainerBuilder();

            // 註冊依賴
            builder.RegisterType<LogInterceptor>(); // 註冊攔截器
            builder.RegisterType<Person>().EnableClassInterceptors();  // 註冊被攔截的類並啟用類攔截

            Container = builder.Build();
        }
        #endregion

5 測試

完整的測試程式碼如下

using System;

using Autofac;
using Autofac.Extras.DynamicProxy;

namespace ConsoleApp_AutofacAop
{
    class Program
    {
        static void Main(string[] args)
        {
            AutofacInit();

            TestMethod();

            Console.ReadLine();
        }

        #region 在應用的啟動地方構造Autofac容器並註冊依賴
        // 定義容器
        private static IContainer Container { get; set; }

        /// <summary>
        /// 初始化Autofac
        /// </summary>
        private static void AutofacInit()
        {
            var builder = new ContainerBuilder();

            // 註冊依賴
            builder.RegisterType<LogInterceptor>(); // 註冊攔截器
            builder.RegisterType<Person>().EnableClassInterceptors();  // 註冊被攔截的類並啟用類攔截

            Container = builder.Build();
        }
        #endregion

        #region 測試方法
        public static void TestMethod()
        {
            Console.WriteLine("使用自己new建立的物件無法使用容器提供的ioc");
            var person1 = new Person();
            person1.Method_NoVirtua();
            person1.Method2();
            person1.Method3("person1_p1", "person1_p2");
            Console.WriteLine();


            using (var scope = Container.BeginLifetimeScope())
            {
                var person = scope.Resolve<Person>();

                person.Method_NoVirtua();
                person.Method2();
                person.Method3("person_p1", "person_p2");
            }
        }
        #endregion
    }
}

執行結果:

注意:只有是Autofac容器建立的物件例項才會被aop攔截,通過其他方法建立的物件例項不會被autofac的aop攔截到

參考資源

https://www.cnblogs.com/li150dan/p/10071079.html