# CS_Unity_QuickStart **Repository Path**: smilly_354/cs_-unity_-quick-start ## Basic Information - **Project Name**: CS_Unity_QuickStart - **Description**: 基于 Unity 模仿 SpringBoot 的快速启动配置框架 - **Primary Language**: Unknown - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-04-10 - **Last Updated**: 2021-04-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Unity.QuickStart ## 1、概述 本项目是基于 Unity IOC 和 AOP 的一个快速使用框架,程序中可以像 SpringBoot 中一样,既可以通过 xml 配置 IOC 和 AOP, 也可以在程序中通过特性标注,程序启动的时候自动扫描注册。 本项目简化了 Unity IOC 和 AOP 的配置。AOP 配置拦截器不在需要继承 IInterceptionBehavior 和 ICallHandler,任意一个类只要标注 [Aspect] 并且在 Advice 方法上标注 [BeforeHandler]、[AfterHandler]、[ExceptionHandler]、[FinallyHandler],Advice 方法需要符合约定的规则。 ## 2、依赖 Unity.Container Unity.Configuration Unity.Abstructions Unity.Interception Unity.Interception.Configuration ## 3、项目配置 在 App.config 中加入 Unity 基本配置,注意:configSections 节点一定要是 configuration 节点下的第一个节点。 ```xml
``` ## 4、IOC 配置 ```c# public interface IPrinter { void Print(); } public class Printer : IPrinter { public void Print() { Console.WriteLine("Printer method Print executing..."); } } /// /// 通过 Configurator 的方式注入 /// [Configurator] public class BeanConfiguration { [Bean(Type = typeof(IPrinter))] public IPrinter Printer() { return new Printer(); } } /// /// 通过 PointCut 标注需要拦截的类 /// public interface IStudent { void Show(); } /// /// 通过 Bean 标注类名自动注入 /// [Bean(Type = typeof(IStudent), LifeTime = LifeTime.Singleton)] public class Student : IStudent { public void Show() { Console.WriteLine("Student method Show executing..."); throw new Exception("Student method Show execute error"); } } ``` ## 5、AOP 配置 第一步,编写切面类,并标注拦截规则 ```c# /// /// 通过 Aspect 标记拦截的方法,并且通过 BeforeHandle 指定处理方法 /// [Aspect(Expression = "pri.smilly.boot.*.*(..)", Order = 0)] public class LoggingHandler { [BeforeHandle] public void Before(IMethodInvocation input) { Console.WriteLine($"before method {input.MethodBase.Name} executing"); } [AfterHandle] public void After(IMethodInvocation input, IMethodReturn result) { Console.WriteLine($"after method {input.MethodBase.Name} executed, result value : {result.ReturnValue}"); } [ExceptHandle] public void Exception(IMethodInvocation input, Exception except) { Console.WriteLine($"method {input.MethodBase.Name} execute whith error : {except.Message}"); } [FinallyHandle] public void Finally(IMethodInvocation input) { Console.WriteLine($"method {input.MethodBase.Name} execution finalize"); } } ``` 第二步,标注目标类。[PointCut] 可以标注在接口上也可以标注在实现类上 ```c# /// /// 通过 PointCut 标注需要拦截的类 /// [PointCut] public interface IStudent { void Show(); } // 效果同上面标注接口一样 [PointCut] [Bean(Type = typeof(IStudent), LifeTime = LifeTime.Singleton)] public class Student : IStudent { public void Show() { Console.WriteLine("Student method Show executing..."); throw new Exception("Student method Show execute error"); } } ```