码迷,mamicode.com
首页 > 其他好文 > 详细

Autofac与AOP功能例子

时间:2019-03-27 18:21:21      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:ISE   default   stat   autofac   etc   show   zhang   ons   static   

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();
        }
    }
}

 技术图片

Autofac与AOP功能例子

标签:ISE   default   stat   autofac   etc   show   zhang   ons   static   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!