Self-implemented simple AOP (4) Automatic initialization of proxy objects, and aop initialization of proxy objects
The first three articles have completed the core functions of AOP, but the initialization of proxy objects is still a little troublesome. This article will solve this problem.
The Demo snippets are as follows:
Public class HomeController: Controller {// <summary> // use Autowired Attribute to automatically initialize the proxy object /// </summary> [Autowired] public Service myService {get; set;} public ActionResult Index () {myService. test (); var msg = myService. errorMsg; Console. writeLine (msg); // Of course, the Code attribute in ServiceException can also be stored in the ServiceAbstract object return View ();}}
In the code snippet above, myService is not assigned a value, but is directly used to call the Test method. When is this attribute assigned?
The answer is: when the MVC Framework and Controller are activated.
In the MVC Framework, Controller activation is completed in DefaultControllerFactory. You can rewrite this class and register it to implement it. When the Controller is activated, the proxy object is automatically initialized.
The Global. asax code is as follows:
// Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 Public class MvcApplication: System. web. httpApplication {protected void Application_Start () {// register a new Controller factory ControllerBuilder. current. setControllerFactory (new MyBatisControllerFactory (); AreaRegistration. registerAllAreas (); WebApiConfig. register (GlobalConfiguration. configuration); FilterConfig. registerGlobalFilters (GlobalFilters. filters); RouteConfig. registerRoutes (RouteTable. routes);} private class MyBatisControllerFactory: DefaultControllerFactory {public override IController CreateController (RequestContext requestContext, string controllerName) {IController controller = base. createController (requestContext, controllerName); // automatically assemble attributes /// <para> enable proxy for the attribute object and delay initializing the object to be proxy </para> DelayProxyUtil. autowiredProperties (controller); return controller ;}}}
Source code: http://files.cnblogs.com/files/08shiyan/AOPDemo.zip
(Self-implemented simple AOP temporarily and will be supplemented later)