.net core-AOP实现日志模块

 nuget 搜索AspectCore.Extentsions.DepencyInjection

using AspectCore.DynamicProxy;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using AspectCore.Extensions.DependencyInjection;


namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceCollection services = new ServiceCollection();
            services.ConfigureDynamicProxy();
            services.AddTransient();

            var provider = services.BuildDynamicProxyProvider();
            var mysql = provider.GetService();
            mysql.GetData(10);

            Console.Read();


            
        }
    }

    public class MyLogInterceptorAttribute : AbstractInterceptorAttribute
    {
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            Console.WriteLine("开始记录日志");
            var task = next(context);
            Console.WriteLine("结束记录日志");

            return task;
        }
    }



    public interface IMySql
    {
        string GetData(int id);
    }


    public class MySql : IMySql
    {
        [MyLogInterceptor]
        public string GetData(int id)
        {
            var msg = $"已经获取到id={id}的数据";
            Console.WriteLine(msg);
            return msg;
        }
    }
}

 

你可能感兴趣的:(.NET,CORE)