使用Unity做类的增强

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

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

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

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

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

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

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

原有业务类

业务模型

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安装。
这里写图片描述
业务增强实现

using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityBehavior
{public class UserProcessorLogBehavior : IInterceptionBehavior{public bool WillExecute{get{return true;}}public IEnumerable<Type> GetRequiredInterfaces(){return Type.EmptyTypes;}public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext){User user = input.Inputs[0] as User;before(user);InvokeInterceptionBehaviorDelegate 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);}}
}

上层调用

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;namespace testAopByUnityBehavior
{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.AddNewExtension<Interception>();container.RegisterType<IUserProcessor, UserProcessor>(new InjectionConstructor(), //构造器拦截new Interceptor<InterfaceInterceptor>(),//注册拦截器new InterceptionBehavior<UserProcessorLogBehavior>() //注册行为拦截);User user = new User { Id = 1, Name = "李丹丹" };//从容器拿到服务(以为加了拦截器,这里生成的是动态对象)IUserProcessor processor = container.Resolve<IUserProcessor>();processor.RegisterUser(user);}}
}

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


这里我们使用代码的方式给原有的业务类配置了拦截器(AOP依赖注入),也可以使用配置文件的方式,这样会更加的灵活。

配置文件:unity.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration><configSections><section name="unity"type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,  Microsoft.Practices.Unity.Configuration"/></configSections><unity xmlns="http://schemas.microsoft.com/practices/2010/unity"><alias alias="singleton"type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" /><sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension,Microsoft.Practices.Unity.Interception.Configuration" /><container>      <extension type="Interception" /><register type="IInterceptionBehavior" mapTo="testAopByUnityConfig.UserProcessorLogBehavior,testAopByUnityConfig" name="UserProcessorLogBehavior"></register><register type="testAopByUnityConfig.IUserProcessor,testAopByUnityConfig" mapTo="testAopByUnityConfig.UserProcessor,testAopByUnityConfig"><interceptionBehavior name="UserProcessorLogBehavior"/><interceptor type="InterfaceInterceptor"/></register></container></unity>
</configuration>

上层调用

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.Unity.InterceptionExtension.Configuration;
using System;
using System.Configuration;namespace testAopByUnityConfig
{class Program{private static User user = new User { Id = 1, Name = "admin" };static void Main(string[] args){RegisterAndLog();Console.ReadKey();}private static void RegisterAndLog(){var map = new ExeConfigurationFileMap { ExeConfigFilename = "unity.config" };//使用此配置文件  var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);var section = (UnityConfigurationSection)config.GetSection("unity");//读取配置文件节点  var container = new UnityContainer();container.LoadConfiguration(section);//从容器拿到服务(因为加了拦截器,这里生成的是动态对象)IUserProcessor processor = container.Resolve<IUserProcessor>();processor.RegisterUser(user);}}
}

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



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

相关文章

setsid 命令工作原理和使用案例介绍

《setsid命令工作原理和使用案例介绍》setsid命令在Linux中创建独立会话,使进程脱离终端运行,适用于守护进程和后台任务,通过重定向输出和确保权限,可有效管理长时间运行的进程,本文给大家介... 目录setsid 命令介绍和使用案例基本介绍基本语法主要特点命令参数使用案例1. 在后台运行命令2.

使用Redis快速实现共享Session登录的详细步骤

《使用Redis快速实现共享Session登录的详细步骤》在Web开发中,Session通常用于存储用户的会话信息,允许用户在多个页面之间保持登录状态,Redis是一个开源的高性能键值数据库,广泛用于... 目录前言实现原理:步骤:使用Redis实现共享Session登录1. 引入Redis依赖2. 配置R

使用Python的requests库调用API接口的详细步骤

《使用Python的requests库调用API接口的详细步骤》使用Python的requests库调用API接口是开发中最常用的方式之一,它简化了HTTP请求的处理流程,以下是详细步骤和实战示例,涵... 目录一、准备工作:安装 requests 库二、基本调用流程(以 RESTful API 为例)1.

使用Python开发一个Ditto剪贴板数据导出工具

《使用Python开发一个Ditto剪贴板数据导出工具》在日常工作中,我们经常需要处理大量的剪贴板数据,下面将介绍如何使用Python的wxPython库开发一个图形化工具,实现从Ditto数据库中读... 目录前言运行结果项目需求分析技术选型核心功能实现1. Ditto数据库结构分析2. 数据库自动定位3

Python yield与yield from的简单使用方式

《Pythonyield与yieldfrom的简单使用方式》生成器通过yield定义,可在处理I/O时暂停执行并返回部分结果,待其他任务完成后继续,yieldfrom用于将一个生成器的值传递给另一... 目录python yield与yield from的使用代码结构总结Python yield与yield

Go语言使用select监听多个channel的示例详解

《Go语言使用select监听多个channel的示例详解》本文将聚焦Go并发中的一个强力工具,select,这篇文章将通过实际案例学习如何优雅地监听多个Channel,实现多任务处理、超时控制和非阻... 目录一、前言:为什么要使用select二、实战目标三、案例代码:监听两个任务结果和超时四、运行示例五

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比