Simple use of Unity Dynamic Loading
Simple use of Unity Dynamic Loading
Unity can be fast and lightweight to achieve IOC, without having to write similar reflection code to dynamically load classes or dll.
Use Unity to obtain reference files with nuget
Unity can configure the content to be dynamically loaded through code or config files.
Example
Static void Main (string [] args) {Console. writeLine ("'y' use Config Register Type, Otherwise use Code Register Type"); bool isUseConfig = Console. readLine (). toUpper (). equals ("Y"); IUnityContainer container = new UnityContainer (); // define the ioc container if (isUseConfig) {// use Config to register Type UnityConfigurationSection configuration = (UnityConfigurationSection) ConfigurationManager. getSection (UnityConfigurationSection. SectionName); configuration. configure (container, "defaultiner iner"); // defaultContainer is the IOC container name defined in config} else {// use code to register Type CodeReg (container );} A a = container. resolve <IA> () as A; // demonstrate dynamic construction of the image B = container. resolve <IB> () as B; var list = new ParameterOverrides (); list. add ("name", "TomMao"); // Parameter name of the constructor. The parameter value is IE e = container. resolve <IE> ("e", list); // demonstrate the constructor passing parameters to construct the Object e. showName (); e = container. res Olve <IE> ("ee", list); // demonstrate how to use different ioc names to construct the same interface image with different classes. ee and e are different ioc names, indicates that different classes are used, and the ioc name e is added during registration. showName (); if (null! = A) {Console. WriteLine ("a. B = null? {0} ", a. B = null? "Yes": "No"); Console. WriteLine ("a. C = null? {0} ", a. C = null? "Yes": "No"); Console. WriteLine ("a. D = null? {0} ", a. D = null? "Yes": "No");} Console. ReadLine ();}
Use code to configure the add-on
// Use code to register private static void CodeReg (IUnityContainer container) {container. registerType (typeof (IA), Type. getType ("UnityDemo. A "); container. registerType (typeof (IB), Type. getType ("UnityDemo. B "); container. registerType (typeof (IC), Type. getType ("UnityDemo. C "); container. registerType (typeof (ID), Type. getType ("UnityDemo. D "); container. registerType (typeof (IE), Type. getType ("UnityDemo. E ")," e "); // Add the registered alias. You can use this name to implement the same interface and different implementations of container. registerType (typeof (IE), Type. getType ("UnityDemo. EE ")," ee ");}
Use Config to configure the add-on