Autofac与AOP功能例子

using Autofac.Extras.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aopTest
{
    [Intercept(typeof(CallLogger))]
    public interface IProduct
    {
        string Title { get; set; }
        decimal Price { get; set; }
        string Show();
    }

    [Intercept(typeof(CallLogger))]
    public class Apple : IProduct
    {
        public Apple()
        {
            Title = "苹果";
            Price = 5.0m;
        }

        public string Title { get ; set ; }
        public decimal Price { get ; set; }

        public virtual string Show()
        {
            return $"{Title} - {Price}";
        }
    }

    [Intercept(typeof(CallLogger))]
    public class Book : IProduct
    {
        public Book()
        {
            Title = "Asp.net开发";
            Price = 35.0m;
        }

        public string Title { get; set; }
        public decimal Price { get; set; }

        [Auth("product.show")]
        public virtual string Show()
        {
            Test();
            return $"{Title} - {Price}";
        }

        protected virtual void Test()
        {
            Console.WriteLine("is a test code....");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aopTest
{
    [AttributeUsage(AttributeTargets.Method)]
    public class AuthAttribute : Attribute
    {
        public AuthAttribute(string code)
        {
            Code = code;
        }
        public string Code { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace aopTest
{
    public class UserInfo
    {
        static LocalDataStoreSlot storeSlot = Thread.AllocateNamedDataSlot("user-info");

        public static void SetUser(string name)
        {
            Thread.SetData(storeSlot, name);
        }

        public static string GetUser()
        {
            return Thread.GetData(storeSlot).ToString();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Castle.DynamicProxy;

namespace aopTest
{
    public class CallLogger : IInterceptor
    {
        TextWriter _output;

        public CallLogger(TextWriter output)
        {
            _output = output;
        }

        public void Intercept(IInvocation invocation)
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            string m = invocation.TargetType.ToString() + "." + invocation.Method.Name;
            _output.WriteLine($"方法:{m}调用开始");
            _output.Write("Calling method {0} with parameters {1}... ",
            invocation.Method.Name,
            string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));

            var authAttribute = invocation.Method.GetCustomAttributes(typeof(AuthAttribute), false).FirstOrDefault();
            if (authAttribute != null)
            {
                var authInfo = (AuthAttribute)authAttribute;
                if (UserInfo.GetUser() != "zhangsan" && authInfo.Code == "product.show")
                {
                    _output.WriteLine($"当前用户{UserInfo.GetUser()}没有方法{m}的访问权限,需要权限{authInfo.Code}");
                }
            }

            invocation.Proceed();
            _output.WriteLine("Done: result was {0}.", invocation.ReturnValue);
            stopWatch.Stop();
            _output.WriteLine($"方法:{m}调用结束,总耗时{stopWatch.ElapsedMilliseconds}毫秒");
        }
    }
}
using Autofac;
using Autofac.Extras.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aopTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            /*builder.RegisterType<Apple>()
                   .As<IProduct>()
                   .EnableInterfaceInterceptors();

            builder.RegisterType<Book>()
                   .As<IProduct>()
                   .EnableInterfaceInterceptors();*/

            builder.RegisterType<Apple>()
                  .As<IProduct>()
                  .EnableClassInterceptors();

            builder.RegisterType<Book>()
                   .As<IProduct>()
                   .EnableClassInterceptors();

            builder.Register(c => new CallLogger(Console.Out));
            var container = builder.Build();

            UserInfo.SetUser("zhaoliu");

            var products = container.Resolve<IEnumerable<IProduct>>();
            products.ToList().ForEach(product => {
                product.Show();
            });

            Console.ReadKey();
        }
    }
}

原文地址:https://www.cnblogs.com/huangzelin/p/10609493.html

时间: 2024-08-03 15:08:10

Autofac与AOP功能例子的相关文章

你相信么,只需一个函数5行JS代码即可在Javascript中实现完整的AOP功能

你相信么,只需一个函数5行JS代码即可在Javascript中实现完整的AOP功能, 你相信么,在JavaScript只需一个函数5行代码即可实现完整的面向方面AOP编程功能.这5行代码的功能包括: 无限层次的函数无害拦截 函数执行前拦截 检查函数的参数值 重新设定函数的参数值 函数执行后拦截 检查函数执行后的返回结果 重新设定函数的返回结果 虽然动态函数式语言的效率是一个存在的问题,但是对于它的高度灵活性,简直让人令人惊叹不已,剧赞. 这个小小的函数源自于和爱明兄的一次讨论:在javascri

C# Unity依赖注入利用Attribute实现AOP功能

使用场景? 很多时候, 我们定义一个功能, 当我们要对这个功能进行扩展的时候, 按照常规的思路, 我们一般都是利用OOP的思想, 在原有的功能上进行扩展. 那么有没有一种东西, 可以实现当我们需要扩展这个功能的时候, 在不修改原来的功能代码的情况下实现, 这就是下面要说的到Unity. 1.准备工作 为项目添加NuGet包, 搜索Unity并且安装. 在使用的项目中添加Unity的相关引用 using Microsoft.Practices.Unity.InterceptionExtension

SpringBoot中使用LoadTimeWeaving技术实现AOP功能

目录 1. 关于LoadTimeWeaving 1.1 LTW与不同的切面织入时机 1.2 JDK实现LTW的原理 1.3 如何在Spring中实现LTW 2. Springboot中使用LTW实现AOP的例子 3. 参考资料 1. 关于LoadTimeWeaving 1.1 LTW与不同的切面织入时机 AOP--面向切面编程,通过为目标类织入切面的方式,实现对目标类功能的增强.按切面被织如到目标类中的时间划分,主要有以下几种: 1.运行期织入 这是最常见的,比如在运行期通过为目标类生成动态代理

java Instrument修改字节码实现aop功能

Agent工程2个类: public class MyAgent { /** * 该方法在main方法之前运行,与main方法运行在同一个JVM中 * 并被同一个System ClassLoader装载 * 被统一的安全策略(security policy)和上下文(context)管理 */ public static void premain(String agentOps, Instrumentation inst) { System.out.println("=========prema

Spring @AspectJ 实现AOP 入门例子(转)

AOP的作用这里就不再作说明了,下面开始讲解一个很简单的入门级例子. 引用一个猴子偷桃,守护者守护果园抓住猴子的小情节. 1.猴子偷桃类(普通类): Java代码   package com.samter.common; /** * 猴子 * @author Administrator * */ public class Monkey { public void stealPeaches(String name){ System.out.println("[猴子]"+name+&quo

使用CGLIB实现AOP功能与AOP概念解释

使用CGLIB实现AOP功能 在Java里面,我们要产生某个对象的代理对象,这个对象必须要有一个特点,即这个对象必须实现一个接口,动态代理技术只能基于接口进行代理.有时候我们在做开发的时候,这个对象就没有实现接口,有人可能会说,它既然没有接口,那我就给它定义一个接口,这是不行的,因为有时候我们拿到一个对象,而这个对象是服务器产生给我们的,是服务器提供给我们的,又不是我们自己写的,动不动就给它定义一个接口,给它找个爸爸,哪那行呢?但我们现在要对它进行增强,这时用动态代理技术就不行了,动态代理技术只

实现AOP功能的封装与配置的小框架

内容 java基础巩固笔记 - 实现AOP功能的封装与配置的小框架 设计(目录): XXX = java.util.ArrayList中 代码 Advice接口 MyAdvice类 BeanFactory类 ProxyFactoryBean类 AopFrameWorkTest类 输出 本文通过是动态代理实现的AOP功能的封装与配置的小框架.加深对动态代理和AOP编程的理解 获取源码,学习交流,那就加入小编的学习交流群吧!616 959 444 设计 根据配置文件的键xxx对应的值(类全名)创建相

FreeSql aop功能介绍

前言 FreeSql 是一个功能强大的 .NETStandard 库,用于对象关系映射程序(O/RM),支持 .NETCore 2.1+ 或 .NETFramework 4.6.1+(QQ群:4336577). 据了解,用户使用很少问问题,编码过程中,因业务阻塞,情有可原:因框架使用问题阻塞,得不偿失.我们的口号:做 .net 最方便的 ORM!愿每一位开发者嘴角上扬??! 整体功能 IFreeSql 是核心,提供原始用法: FreeSql.DbContext 是扩展包,提供面向对象的用法(像E

[开源] FreeSql AOP 功能模块

前言 FreeSql 是一个功能强大的 .NETStandard 库,用于对象关系映射程序(O/RM),支持 .NETCore 2.1+ 或 .NETFramework 4.6.1+(QQ群:4336577). 据了解,用户使用很少问问题,编码过程中,因业务阻塞,情有可原:因框架使用问题阻塞,得不偿失.我们的口号:做 .net 最方便的 ORM!愿每一位开发者嘴角上扬??! 整体功能 IFreeSql 是核心,提供原始用法: FreeSql.DbContext 是扩展包,提供面向对象的用法(像E