Back to Catalog
The previous Unity article was primarily a basic implementation, and there was no particular place where unity could easily implement the IOC control inversion of the application, which gave our application a higher degree of coupling and increased testability, of course, the premise of which is interface-oriented programming, If you are facing the specific implementation to write the program, then you do not have to read this article, hehe.
This article mainly share, through the unity component of the service locator servicelocator to achieve bulk load type, that you do not have their configuration to the config file, even when dynamic loading, but also for it to add some behavior, such as caching, hehe!
Here's the idea of realization.
First Unity has its own easy unitycontainer, and our configuration information is added to it, exposing the Registertype method to register the type and behavior (AOP) in the container, This is how we extract all of the interface implementation classes from the specified DLL in the application's Bin directory and add them to the UnityContainer container, which enables the batch dynamic registration type!
My project. IOC project structure (from warehouse Uncle Frame set)
Modify the contents of a Servicelocator file
Added the specified private method to do this.
/// <summary> ///loading a batch of dynamic types///author:zhangzhanling///date:2015-04-03/// </summary> Private voidLoaddynamictype (Iunitycontainer _container) {//Unity dynamic Type injection, each assembly used, separate, support * wildcard symbols stringunitydynamicassembly = system.configuration.configurationmanager.appsettings["unitydynamicassembly"]; //whether to start the data set cache policy at the same time stringunitycachingdoing = system.configuration.configurationmanager.appsettings["unitycachingdoing"]; Injectionmember[] Injectionmembers=NULL; if(Unitycachingdoing = ="1") {injectionmembers=NewInjectionmember[] {NewInterceptor<interfaceinterceptor> (),NewInterceptionbehavior<project.unitycaching.cachingbehavior>() }; } if(!string. Isnullorwhitespace (unitydynamicassembly)) {Array.foreach (Unitydynamicassembly.split (New Char[] {','}, stringsplitoptions.removeemptyentries), DllName = { varBaseDir =AppDomain.CurrentDomain.BaseDirectory; if(System.Web.HttpContext.Current! =NULL) {BaseDir+="bin"; } varFiles =Directory.GetFiles (BaseDir, dllName); varItypes =NewList<type>(); foreach(varFileinchfiles) { varInterfaceasm =Assembly.LoadFrom (Path.Combine (baseDir, file)); varTypes = fromTinchinterfaceasm.gettypes ()where!string. Isnullorwhitespace (T.namespace)SelectT; foreach(varTypeinchtypes) { if(Type. Getinterfaces ()! =NULL&&type. Getinterfaces (). Any ())foreach(varFatherinchtype. Getinterfaces ()) {_container. Registertype (father, type, Injectionmember s); } } } }); } }
Call it in Servicelocator
It's done, haha!
Back to Catalog
16th IOC Component Unity Continuation ~ Batch dynamic add type and behavior to unity