Unity of the IOC

Source: Internet
Author: User

I. What is ICC?

The IoC (inversion of control, controlled inversion) is also known as "Dependency Injection" (dependence injection,di).

Control inversion is the right to create an object that is controlled by the developer and moved to the container.

Dependency injection is the creation of objects through containers, which are injected by means of parameters, property settings, and interfaces of the constructor method.

The basic concept of the IOC is that it does not create objects, but describes how they are created. You do not directly connect to objects and services in your code, but in configuration files (or programs) that describe creating relationships, the container is responsible for connecting them.

Second, what is unity?

Unity is a lightweight, extensible IOC framework developed by Microsoft that configures the direct relationships between objects and objects in the form of code or XML configuration files.

Call the container directly at runtime to get the objects we need to build a loosely coupled program.

Third, create Unity Demo

1. Create a new console project Unitydemo

2. Right-Unitydemo The project and select "Manage NuGet packages" To install the unity package

3. Create several interfaces Iphone,iheadphone,imicrophone,ipower

 Public InterfaceIheadphone {} Public InterfaceImicrophone {} Public InterfaceIPower {} Public InterfaceIPhone {/// <summary>        ///Call/// </summary>        voidCall (); Imicrophone Imicrophone {Get;Set; } Iheadphone Iheadphone {Get;Set; } IPower IPower {Get;Set; } }

4. New class for inheriting interfaces

  Public classHeadphone:iheadphone {} Public classMicrophone:imicrophone {} Public classPower:ipower {} Public classAndroidphone:iphone { PublicIheadphone Iheadphone {Get;Set; }  PublicImicrophone Imicrophone {Get;Set; }  PublicIPower IPower {Get;Set; }  PublicAndroidphone () {Console.WriteLine ("{0} constructor", This. GetType ().        Name); }         Public voidCall () {Console.WriteLine ("{0} call", This. GetType ().         Name); }    } Public classApplephone:iphone {[Dependency]//Attribute Injection         PublicIheadphone Iheadphone {Get;Set; }  PublicImicrophone Imicrophone {Get;Set; }  PublicIPower IPower {Get;Set; }  PublicApplephone () {Console.WriteLine ("{0} constructor", This. GetType ().        Name); } [Injectionconstructor]//Constructor Injection         PublicApplephone (Imicrophone imicrophone) { This. Imicrophone =Imicrophone; Console.WriteLine ("{0} with parameter constructors", This. GetType ().        Name); }         Public voidCall () {Console.WriteLine ("{0} call", This. GetType ().        Name); } [Injectionmethod]//Attribute Injection         Public voidInit (IPower IPower) { This. IPower =IPower; }    }

Four, the registration of the corresponding relationship of the program

There are three ways to inject unity: 1. Attribute injection, using [Dependency] attribute 2. Constructs method injection, using the [Injectionconstructor] attribute (without this attribute, the default uses the most parameters of the construction method) 3. Method injection, using [ Injectionmethod] Properties

1. Create a UnityContainer object

2. Register the relationship between objects and objects through the Registertype method of the UnityContainer object

3. Get the object associated with the specified object by using the Resolve method of the UnityContainer object

Static voidMain (string[] args) {            Try{Console.WriteLine ("********************androidphone**********************"); {Iunitycontainer container=NewUnityContainer (); Container. Registertype<iphone, androidphone>(); Container. Registertype<iheadphone, headphone>(); Container. Registertype<imicrophone, microphone>(); Container. Registertype<ipower, power>(); IPhone Phone= Container. Resolve<iphone>(); Phone.                    Call (); //non-injected Iheadphone,imicrophone,ipower objects are emptyConsole.WriteLine ("Phone.iheadphone = = null? {0}", Phone.iheadphone = =NULL); Console.WriteLine ("Phone.imicrophone = = null? {0}", Phone.imicrophone = =NULL); Console.WriteLine ("Phone.ipower = = null? {0}", Phone.ipower = =NULL); } Console.WriteLine ("********************applephone**********************"); {Iunitycontainer container=NewUnityContainer (); Container. Registertype<iphone, applephone>(); Container. Registertype<iheadphone, headphone>(); Container. Registertype<imicrophone, microphone>(); Container. Registertype<ipower, power>(); IPhone Phone= Container. Resolve<iphone>(); Phone.                    Call (); //through attribute injection, constructor injection, method injection Iheadphone,imicrophone,ipower object is not emptyConsole.WriteLine ("Phone.iheadphone = = null? {0}", Phone.iheadphone = =NULL); Console.WriteLine ("Phone.imicrophone = = null? {0}", Phone.imicrophone = =NULL); Console.WriteLine ("Phone.ipower = = null? {0}", Phone.ipower = =NULL); }            }            Catch(Exception ex) {Console.WriteLine (ex).            Message);        } console.readkey (); }

Operation Result:

V. Configuring correspondence through configuration Files

Project structure:

Configuration file:

<?xml version="1.0"encoding="Utf-8"?><configuration> <configSections> <section name="Unity"Type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration "/> </configSections> <unity> <!--definition aliases--<aliases> <add alias="IPhone"Type="Unitydemo.interface.iphone,unitydemo"/> <add alias="Iheadphone"Type="Unitydemo.interface.iheadphone,unitydemo"/> <add alias="Imicrophone"Type="Unitydemo.interface.imicrophone,unitydemo"/> <add alias="IPower"Type="Unitydemo.interface.ipower,unitydemo"/> <add alias="Androidphone"Type="Unitydemo.service.androidphone,unitydemo"/> <add alias="Applephone"Type="Unitydemo.service.applephone,unitydemo"/> <add alias="headphone"Type="Unitydemo.service.headphone,unitydemo"/> <add alias="Microphone"Type="Unitydemo.service.microphone,unitydemo"/> <add alias="Power"Type="Unitydemo.service.power,unitydemo"/> </aliases> <!--containers--<container name="MyContainer"> <!--mapping Relationship--<register type="IPhone"mapto="Applephone"/> <register type="Iheadphone"mapto="headphone"/> <register type="Imicrophone"mapto="Microphone"/> <register type="IPower"mapto="Power"/> </container> </unity></configuration>

Calling code:

 Public Static voidcontainerconfiguration () {Iunitycontainer container=NewUnityContainer (); Execonfigurationfilemap Filemap=NewExeconfigurationfilemap {execonfigfilename ="Unity.config"}; Configuration Configuration=configurationmanager.openmappedexeconfiguration (Filemap, Configurationuserlevel.none); Unityconfigurationsection Section= (unityconfigurationsection) configuration. GetSection ("Unity"); Container. Loadconfiguration (section,"MyContainer"); IPhone Phone= Container. Resolve<iphone>(); Phone.            Call (); //through attribute injection, constructor injection, method injection Iheadphone,imicrophone,ipower object is not emptyConsole.WriteLine ("Phone.iheadphone = = null? {0}", Phone.iheadphone = =NULL); Console.WriteLine ("Phone.imicrophone = = null? {0}", Phone.imicrophone = =NULL); Console.WriteLine ("Phone.ipower = = null? {0}", Phone.ipower = =NULL); }

Unity of the IOC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.