I. Introduction of the IOC
IOC (inversion of Control), translated in Chinese as controlled inversion, also known as "Dependency Injection" (DI =dependence injection)
The basic concept of the IOC is that it does not create objects, but describes how they are created. The code does not directly connect to objects and services, but describes in the configuration file which component requires which service. The container is responsible for linking these together.
The principle is based on the OO design principle of the Hollywood Principle:don ' t call us, we'll call you (don't find me, I'll come to you). In other words, all components are passive (Passive), and all component initialization and invocation are the responsibility of the container. The component is in a container and is managed by the container.
Simply put, the application itself is not responsible for the creation and maintenance of dependent objects, but rather it is entrusted to an external container. Thus control is transferred from the application to the external IOC container, that is, control to achieve the so-called reversal. For example, an instance of type B needs to be used in type A, and a B instance is created not by a, but by an external container. It is significant to realize the activation of target controller by IOC.
Second, get Unity
The current popular IOC framework, such as AUTOFAC, Castle Windsor, Unity, Spring.net, StructureMap, and Ninject. Unity's address on CodePlex is http://unity.codeplex.com/, and we can download the appropriate installation package and development documentation. Of course, if you have the NuGet Package Manager installed in your Visual Studio, you can get the latest version of unity directly from NuGet.
Iii. Introduction of Unity
Unit is a lightweight, extensible dependency injection container implemented by the Microsoft patterns& Practices group in C #, where we can configure the relationship between objects and objects in the form of code or XML configuration files. Call the Unity container directly at run time to get the objects we need to build loosely coupled applications.
For small projects: implemented in code
For medium to large projects: Using a configuration file is better
Since unity is an IOC framework, he also satisfies the IOC's commonality, which is divided into 3 forms: constructor injection, attribute (set) injection, and interface injection.
Iv. Unity API
Unitycontainer.registertype<itfrom,tto> ();
unitycontainer.registertype< Itfrom, TTO > ();
unitycontainer.registertype< Itfrom, TTO > ("KeyName");
ienumerable<t> databases = unitycontainer.resolveall<t> ();
IT instance = unitycontainer.resolve<it> ();
T instance = unitycontainer.resolve<t> ("KeyName");
Unitcontainer.registerinstance<t> ("KeyName", New T ());
Unitycontainer.buildup (existinginstance);
Iunitycontainer childContainer1 = Parentcontainer.createchildcontainer ();
V. Use of untiy
If you are using a Nugut installed Unity Library, you will automatically be added in the project
Microsoft.Practices.Unity.dll and Microsoft.Practices.Unity.Configuration.dll and Microsoft.Practices.Unity.RegistrationByConven References to tion
New console program Unitydemo, and then create a new interface iproduct, two classes milk, Sugar
/// <summary> ///Product/// </summary> Public Interfaceiproduct {stringClassName {Get;Set; } voidShowinfo (); } /// <summary> ///Milk/// </summary> Public classmilk:iproduct { Public stringClassName {Get;Set; } Public voidShowinfo () {Console.WriteLine ("milk: {0}", ClassName); } } /// <summary> ///Sugar/// </summary> Public classsugar:iproduct { Public stringClassName {Get;Set; } Public voidShowinfo () {Console.WriteLine ("sugar: {0}", ClassName); } }
(1) The injection is realized by means of programming
Using Unity to manage the relationship between objects and objects can be divided into the following steps:
A. Create a UnityContainer object
B. Register the relationship between objects and objects through the Registertype method of the UnityContainer object
C. Get the object associated with the specified object by the Resolve method of the UnityContainer object
The injected code is as follows:
/// <summary> ///Code Injection/// </summary> Public Static voidContainercode () {Iunitycontainer container=NewUnityContainer (); Container. Registertype<iproduct, milk> ();//Default registration (no naming), if there is a default registration will overwrite the previousContainer. Registertype<iproduct, Sugar> ("Sugar");//Name Registrationiproduct _product= Container. Resolve<iproduct> ();//Resolving default Objects_product. ClassName =_product. GetType (). ToString (); _product. Showinfo (); IProduct _sugar= Container. Resolve<iproduct> ("Sugar");//specifying named resolution Objects_sugar. ClassName =_sugar. GetType (). ToString (); _sugar. Showinfo (); IEnumerable<IProduct> classlist = container. Resolveall<iproduct> ();//gets the registered named object for all iproduct in the container foreach(varIteminchclasslist) {Item. ClassName=item. GetType (). ToString (); Item. Showinfo (); } }
Prome.cs:
class program { staticvoid Main (string[] args) { containercode (); } }
As follows:
(2) configuration file mode
There are several steps required to configure unity information through the configuration file:
A. Register the section named Unity under the configuration files <configSections> configurations
B. Add Unity configuration information under the <configuration> configuration section
C. Read the configuration information in the code and load the configuration into UnityContainer
The contents of the configuration file are as follows:
<?XML version= "1.0" encoding= "Utf-8"?><Configuration> <configsections> < Sectionname= "Unity"type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration "/> </configsections> <Unity> <!--Defining type Aliases - <aliases> <Addalias= "IProduct"type= "Unitydemo.iproduct,unitydemo" /> <Addalias= "Milk"type= "Unitydemo.milk,unitydemo" /> <Addalias= "Sugar"type= "Unitydemo.sugar,unitydemo" /> </aliases> <!--Container - <Containername= "MyContainer"> <!--Mapping Relationships - <Registertype= "IProduct"Mapto= "Milk"></Register> <Registertype= "IProduct"Mapto= "Sugar"name= "Sugar"></Register> </Container> </Unity> <!--<startup> <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/> </startup> -</Configuration>
Add System.Configuration Reference First
Configuration File Injection Code:
///<Summary>/// config file injection //</Summary>Public static void Containerconfiguration () {Iunitycontainer container = new UnityContainer (); Container. Loadconfiguration ("MyContainer"); Unityconfigurationsection section = (unityconfigurationsection) configurationmanager.getsection ("Unity");//gain means Configuration section for the name. Configure (Container, "MyContainer");//Gets the configuration section named under a specific configuration<Containername= ' MyContainer '>the configuration information under iproduct ClassInfo = container. Resolve<iproduct>("Sugar"); Classinfo.showinfo (); }
If the system is large, the dependencies between objects can be complex, eventually causing the configuration file to become large, So we need to separate the configuration information for unity from App. Config or Web. config into a separate configuration file, such as Unity.config, which can be referenced in the following code
#regionIunitycontainer Container=NewUnityContainer (); stringConfigFile ="Unity.config"; varFilemap =NewExeconfigurationfilemap {execonfigfilename =ConfigFile}; //reading configuration information from the config fileConfiguration Configuration =configurationmanager.openmappedexeconfiguration (Filemap, Configurationuserlevel.none); //Gets the configuration section for the specified nameUnityconfigurationsection section = (unityconfigurationsection) configurationmanager.getsection ("Unity"); //load container node with name FirstClassContainer. Loadconfiguration (section,"MyContainer"); #endregion
Introduction to Unity, the first to write this today, more content, not to be continued ...
Unity of the IOC framework