使用Unity做类的增强(续)

2023-12-09 21:49
文章标签 使用 unity 增强 做类

本文主要是介绍使用Unity做类的增强(续),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我们已经实现了用户注册功能,现在想增加日志记录功能。具体来讲就是在用户注册前后,分别输出一条日志。我们当然可以修改原有的业务代码。

现在换个角度来问两个问题:
1. 团队开发中,我们很可能根本拿不到源代码,那又怎么去增加这个功能呢?
2. 这次需求是增加日志,以后再增加其他需求(比如异常处理),是不是仍然要改业务类呢?

总结一下:
我们要在不修改原有类业务代码的前提下,去做类的增强。我们的设计要符合面向对象的原则:对扩展开放,对修改封闭

都有哪些办法呢?我们尝试以下几种方法:

  • 使用装饰器模式做类的增强
  • 使用.Net代理模式做类的增强
  • 使用Castle做类的增强
  • 使用Unity做类的增强
  • 使用Unity做类的增强(续)
  • 使用Autofac做类的增强

上次我们使用unity实现了log日志的增强,这次我们来实现异常处理、权限验证两个需求;并且不使用拦截器的方式,而是使用Attribute给原有业务类来打标签的方式来达到业务增强的目的。

原有业务类

业务模型

namespace testAopByDecorator
{public class User{public string Name { get; set; }public int Id { get; set; }}
}

接口设计

namespace testAopByDecorator
{public interface IUserProcessor{void RegisterUser(User user);}
}

业务实现

using System;namespace testAopByDecorator
{public class UserProcessor : IUserProcessor{public void RegisterUser(User user){if (user == null){return;}Console.WriteLine(string.Format("注册了一个用户{0}:{1}", user.Id, user.Name));}}
}

上层调用

using System;namespace testAopByDecorator
{class Program{private static User user = new User { Id = 1, Name = "滇红" };static void Main(string[] args){Register();Console.ReadKey();}private static void Register(){IUserProcessor processor = new UserProcessor();processor.RegisterUser(user);}}
}

使用Unity做类的增强

我们将使用第三方的Unity来对原有的类做业务增强,首先使用NuGet安装。
这里写图片描述

日志Attribute类

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityAttribute
{public class LogHandlerAttribute : HandlerAttribute{public override ICallHandler CreateHandler(IUnityContainer container){ICallHandler handler = new UserProcessorLog { Order = this.Order };return handler;}}public class UserProcessorLog : ICallHandler{public int Order { get; set; }public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext){User user = input.Inputs[0] as User;before(user);InvokeHandlerDelegate delegateMethod = getNext();IMethodReturn returnMessag = delegateMethod(input, getNext);after(user);return returnMessag;}private void after(User user){Console.WriteLine("日志结束:" + user.Name);}private void before(User user){Console.WriteLine("日志开始:" + user.Name);}}
}

异常Attribute类

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityAttribute
{public class ExceptionHandlerAttribute : HandlerAttribute{public override ICallHandler CreateHandler(IUnityContainer container){ICallHandler handler = new UserProcessorException { Order = this.Order };return handler;}}public class UserProcessorException : ICallHandler{public int Order { get; set; }public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext){User user = input.Inputs[0] as User;before(user);InvokeHandlerDelegate delegateMethod = getNext();IMethodReturn returnMessag = delegateMethod(input, getNext);if (returnMessag.Exception != null){Console.WriteLine("捕获了异常:" + returnMessag.Exception.Message);returnMessag.Exception = null; //结束异常栈}after(user);return returnMessag;}private void after(User user){Console.WriteLine("异常捕获后:" + user.Name);}private void before(User user){Console.WriteLine("异常捕获前:" + user.Name);}}
}

权限Attribute类

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityAttribute
{public class AuthorizeHandlerAttribute : HandlerAttribute{public override ICallHandler CreateHandler(IUnityContainer container){ICallHandler handler = new UserProcessorAuthorize { Order = this.Order };return handler;}}public class UserProcessorAuthorize : ICallHandler{public int Order { get; set; }public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext){User user = input.Inputs[0] as User;Console.WriteLine("权限验证中......");if(user == null || !user.Name.Equals("admin")){//抛出异常return input.CreateExceptionMethodReturn(new Exception("没有这个用户!"));}before(user);InvokeHandlerDelegate delegateMethod = getNext();IMethodReturn returnMessage = delegateMethod(input, getNext);after(user);return returnMessage;}private void after(User user){Console.WriteLine("用户注册后:" + user.Name);}private void before(User user){Console.WriteLine("用户注册前:" + user.Name);}}
}

给业务接口打标签,原有业务类会自动继承

namespace testAopByUnityAttribute
{//使用Order来决定特性的执行时序[ExceptionHandler(Order =1)][LogHandler(Order = 2)][AuthorizeHandler(Order =3)]public interface IUserProcessor{void RegisterUser(User user);}
}

上层调用

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;namespace testAopByUnityAttribute
{class Program{private static User user = new User { Id = 1, Name = "admin" };static void Main(string[] args){RegisterAndLog();Console.ReadKey();}private static void RegisterAndLog(){//创建容器IUnityContainer container = new UnityContainer();//注册服务container.RegisterType<IUserProcessor, UserProcessor>();//扩展拦截器container.AddNewExtension<Interception>().Configure<Interception>().SetInterceptorFor<IUserProcessor>(new InterfaceInterceptor());//调用服务IUserProcessor processor = container.Resolve<IUserProcessor>();try{processor.RegisterUser(user);}catch (Exception ex){Console.WriteLine(ex.Message);}}}
}

对比一下扩展前后的业务展现
这里写图片描述

这篇关于使用Unity做类的增强(续)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/475194

相关文章

使用Python将PDF表格自动提取并写入Word文档表格

《使用Python将PDF表格自动提取并写入Word文档表格》在实际办公与数据处理场景中,PDF文件里的表格往往无法直接复制到Word中,本文将介绍如何使用Python从PDF文件中提取表格数据,并将... 目录引言1. 加载 PDF 文件并准备 Word 文档2. 提取 PDF 表格并创建 Word 表格

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA

Python使用Matplotlib和Seaborn绘制常用图表的技巧

《Python使用Matplotlib和Seaborn绘制常用图表的技巧》Python作为数据科学领域的明星语言,拥有强大且丰富的可视化库,其中最著名的莫过于Matplotlib和Seaborn,本篇... 目录1. 引言:数据可视化的力量2. 前置知识与环境准备2.1. 必备知识2.2. 安装所需库2.3

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

Linux内核定时器使用及说明

《Linux内核定时器使用及说明》文章详细介绍了Linux内核定时器的特性、核心数据结构、时间相关转换函数以及操作API,通过示例展示了如何编写和使用定时器,包括按键消抖的应用... 目录1.linux内核定时器特征2.Linux内核定时器核心数据结构3.Linux内核时间相关转换函数4.Linux内核定时

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java使用Spire.Doc for Java实现Word自动化插入图片

《Java使用Spire.DocforJava实现Word自动化插入图片》在日常工作中,Word文档是不可或缺的工具,而图片作为信息传达的重要载体,其在文档中的插入与布局显得尤为关键,下面我们就来... 目录1. Spire.Doc for Java库介绍与安装2. 使用特定的环绕方式插入图片3. 在指定位

Springboot3 ResponseEntity 完全使用案例

《Springboot3ResponseEntity完全使用案例》ResponseEntity是SpringBoot中控制HTTP响应的核心工具——它能让你精准定义响应状态码、响应头、响应体,相比... 目录Spring Boot 3 ResponseEntity 完全使用教程前置准备1. 项目基础依赖(M

Java使用Spire.Barcode for Java实现条形码生成与识别

《Java使用Spire.BarcodeforJava实现条形码生成与识别》在现代商业和技术领域,条形码无处不在,本教程将引导您深入了解如何在您的Java项目中利用Spire.Barcodefor... 目录1. Spire.Barcode for Java 简介与环境配置2. 使用 Spire.Barco