zoukankan      html  css  js  c++  java
  • NETCore 实现AOP

    1:静态方式(装饰模式或者代理模式)

    Model:

    public class User
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

    IUserservice:

     public interface IUserService
        {
            bool AddUser(User user);
        }
        //[Intercept(typeof(AutoFacInterceptAOP))]
        public class UserService : IUserService
        {
            public bool AddUser(User user)
            {
                Console.WriteLine($"用户添加成功:{user.Name}");
                return true;
            }
        }

    装饰/代理:

    //静态代理
        //代理模式或者装饰者模式实现
        public class ProxyAOP : IUserService
        {
            IUserService _userService; //= new UserService();
            public bool AddUser(User user)
            {
                Before();
                //正式的逻辑
                //  throw new NotImplementedException();
                After();
                return true;
            }
            public void Before()
            { }
            public void After()
            { }
        }
    
        public class DecoratorAOP : IUserService
        {
            IUserService _userService; //= new UserService();
            public DecoratorAOP(IUserService _userService)
            {
                this._userService = _userService;
            }
            public bool AddUser(User user)
            {
                Before();
                //正式的逻辑
                _userService.AddUser(user);
                //  throw new NotImplementedException();
                After();
                return true;
            }
            public void Before()
            { }
            public void After()
            { }
        }

    使用:

      IUserService userService1 = new ProxyAOP();
                userService1.AddUser(new User() { Name="fanlin"});

    2:动态代理(DispatchProxy)

    public class DynamicAgent : DispatchProxy
        {
            //具体类型
            public object TargetClass { get; set; }
            protected override object Invoke(MethodInfo targetMethod, object[] args)
            {
                Console.WriteLine("增加用户前执行业务");
                Before();
                //调用原有方法
                targetMethod.Invoke(TargetClass, args);
    
                Console.WriteLine("增加用户后执行业务");
    
                After();
                return true;
            }
            public void Before()
            { }
            public void After()
            { }
        }

    使用:

     IUserService userService = DispatchProxy.Create<IUserService, DynamicAgent>();
                ((DynamicAgent)userService).TargetClass = new UserService();
                userService.AddUser(new User() { Name = "DispatchProxy动态代理" });

    3:Castle.Core

     //引入库 做动态代理 Castle.Core
        public class InterceptAOP : IInterceptor
        {
            public void Intercept(IInvocation invocation)
            {
                Before();
                // //调用下一个拦截器直到目标方法
                invocation.Proceed();
                After();
                //throw new NotImplementedException();
            }
            public void Before()
            {
    
                Console.WriteLine("Castle.Core拦截前");
            }
            public void After()
            { Console.WriteLine("Castle.Core拦截后"); }
        }

    使用:

       ProxyGenerator proxyGenerator = new ProxyGenerator();
                IUserService u = proxyGenerator.CreateInterfaceProxyWithTarget<IUserService>(new UserService(), new InterceptAOP());
                u.AddUser(new User() { Name = "Castle.Core动态代理" });

    4:Autofac实现

     //需要引入 AutoFac   Autofac.Extras.DynamicProxy (AOP相关组件,包含了Castle.Core) Autofac.Extensions.DependencyInJection
        public class AutoFacInterceptAOP : IInterceptor
        {
            public void Intercept(IInvocation invocation)
            {
                Before();
    
                // //调用下一个拦截器直到目标方法
                invocation.Proceed();
                After();
                //throw new NotImplementedException();
            }
            public void Before()
            {
                Console.WriteLine("AutofacAOP调用方法之前做验证");
            }
            public void After()
            {
                Console.WriteLine("AutofacAOP调用方法之后告知成功");
            }
        }

    使用

     var builder = new ContainerBuilder();
                // 命名注入
                //builder.Register(c => new AutoFacInterceptAOP()).Named<IInterceptor>("log-calls");
    
                ////类型注入
                builder.Register(c => new AutoFacInterceptAOP());
                //或者
                //builder.RegisterType<AutoFacInterceptAOP>();
    
                //启用类代理拦截
                //方式一:给类型上加特性Attribute 类代理拦截的方法必须是虚方法
                builder.RegisterType<AutofacTestMethod>().EnableClassInterceptors();
    
                // builder.Register(c => new AutofacTestMethod { Name = "类代理拦截" });
                //方式二:在注册类型到容器的时候动态注入拦截器(去掉类型上的特性Attribute)
                //builder.RegisterType<AutofacTestMethod>()
                //    .InterceptedBy(typeof(AutoFacInterceptAOP))
                //    .EnableClassInterceptors();
    
                ////启用接口代理拦截
                //这样 使用别名
                //builder.RegisterType<UserService>().Named<IUserService>("UserSer").EnableInterfaceInterceptors();
                //不用加 特性
                builder.RegisterType<UserService>().As<IUserService>().InterceptedBy(typeof(AutoFacInterceptAOP)).EnableInterfaceInterceptors();
                //需要 加特性
                // builder.RegisterType<UserService>().As<IUserService>().EnableInterfaceInterceptors();
                using (var container = builder.Build())
                {
                    //第一种
                    //IUserService userService = container.Resolve<IUserService>();
                    //userService.AddUser(new User() { Name = "Autofac AOP" });
                    //第二种
                    using (var scope = container.BeginLifetimeScope())
                    {
                        //IUserService userService = scope.Resolve<IUserService>();
                        //userService.AddUser(new User() { Name = "Autofac AOP" });
                        //类代理拦截
                        AutofacTestMethod autofacTestMethod = scope.Resolve<AutofacTestMethod>();
                        autofacTestMethod.Name = "类代理拦截";
                        autofacTestMethod.Say();
                        //var cat = scope.ResolveNamed<IUserService>("UserSer");
                        //cat.AddUser(new User() { Name = "Autofac AOP 别名" });
                    }
                }

    如果是NetCoreApi

    1:首先在StartUp中新建方法

     public void ConfigureContainer(ContainerBuilder builder)
            {
                //注册用户维护业务层
                var basePath = AppContext.BaseDirectory;
                var serviceDll = Path.Combine(basePath, "AOPService.dll");
    
                if (!File.Exists(serviceDll))
                {
                    throw new Exception("找不到程序集");
                }
                builder.RegisterType(typeof(AOPService));
                //下面两种方式一样
                builder.RegisterAssemblyTypes(Assembly.LoadFrom(serviceDll))
                    .AsImplementedInterfaces()
                   .InterceptedBy(typeof(AOPService))
                    .EnableInterfaceInterceptors();
                //builder.RegisterType<UserService>().As<IUserService>().InterceptedBy(typeof(AOPService)).EnableInterfaceInterceptors();
                //builder.RegisterType<TableService>().As<ITableService>().InterceptedBy(typeof(AOPService)).EnableInterfaceInterceptors();
                Console.WriteLine("注入");
            }

    2:Program中添加

      public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                //需要引入Autofac.Extensions.DependencyInjection, 这里重要,不然Autofac不管用
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        //webBuilder.RegisterType<CustomInterceptor>();
                        //webBuilder.RegisterType<CustomerService>().As<ICustomerService>().InstancePerLifetimeScope();
                        webBuilder.UseStartup<Startup>();
                    });

    3:在Controller中引用并使用

      public WeatherForecastController(IUserService userService, ITableService tableService)
            {
                _userService = userService;
                _tableService = tableService;
            }
    
    
    
      [HttpGet]
            public IEnumerable<WeatherForecast> Get()
            {
                _userService.AddUser(new User() { Name = "fanlin" });
                _tableService.DeleteUser(new User() { Name="fanlin"});
                var rng = new Random();
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }

    中间件实现:

     /// <summary>
        /// 中间件实现 需要在StartUP - Configure里面添加中间件
        /// </summary>
        public class AopMiddleware
        {
    
            private readonly RequestDelegate _next;
            public AopMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task InvokeAsync(HttpContext context)
            {
                Preproceed(context);
                if (context.Request.Method.ToString().ToLower().Equals("get"))
                {
                    Console.WriteLine($"现在的请求是{context.Request.Method.ToString()}");
                }
                //执行Action
                await _next(context);
                Postproceed(context);
            }
            private void Preproceed(HttpContext context)
            {
                Console.WriteLine($"{DateTime.Now} middleware invoke preproceed");
    
            }
    
    
    
            private void Postproceed(HttpContext context)
            {
                Console.WriteLine($"{DateTime.Now} middleware invoke postproceed");
            }
    
        }

    运行:每一次调用接口之后都会执行

    最后感谢: 1:https://www.cnblogs.com/li150dan/p/10071079.html  2:https://www.cnblogs.com/zoe-zyq/p/12803450.html

  • 相关阅读:
    51nod 1163 最高的奖励
    51nod 1191 消灭兔子
    51nod 2538 二三排列
    node做渲染服务器的实现
    gulp静态服务器的搭建
    canvas中裁切(橡皮檫)的应用--探照灯,点击去除遮罩
    canvas中图片、视频的加载(截图、切片)
    canvas中笔触基础知识
    Gitee的使用流程
    gulp的使用
  • 原文地址:https://www.cnblogs.com/fanlin92/p/15593268.html
Copyright © 2011-2022 走看看