[IOC Container Unity] Third back: Dependency Injection

Source: Internet
Author: User

The previous section describes the lifetime managers life cycle of unity, where unity specifically implements dependency injection including constructor injection, attribute injection, method injection, and so-called injection of a fairly assigned value, as described in one of the following.

2. Constructor injection

Unity uses the Resolve method to parse an object, which is initialized by invoking a constructor of the registered type, and when initialized, unity can control the initialized value, and of course, we want to provide unity with enough raw material, otherwise it's tricky to bricks without straw, and here are some simple examples.

Let's prepare several classes as follows:

    <summary>///class interface///</summary> public interface IClass {string ClassName {get; Set    } void Showinfo (); }///<summary>/////</summary> public class Cbclass:iclass {public string Cla        ssname {get; set;}        public void Showinfo () {Console.WriteLine ("To be a preparatory: {0}", ClassName); }}///<summary>//Shangban///</summary> public class Ecclass:iclass {public Strin        G ClassName {get; set;}        public void Showinfo () {Console.WriteLine ("Electric Shangban: {0}", ClassName); }}///<summary>//Student interface///</summary> public interface Istudent {string Name {g Et Set    }//Attend class void Showinfo (); }///<summary>//Students///</summary> public class Qlinstudent:istudent {public Strin        G Name {get; set;} Private IClass toclass {get; SET        } public qlinstudent (IClass _class) {toclass = _class;        } public void Showinfo () {Console.WriteLine ("{0} enrolled in class: {1}", Name, Toclass.classname); }    }

is a class and student structure, now we have to parse a student istudent, we see the concrete student class Qlinstudent's constructor needs a class interface, of course, to provide this class map to Iunitycontainer container and students own mapping, Just what you want, first of all to provide iunitycontainer what stuff.

2.1 Default mode

The default way with new object, it will be based on the material you provide, choose a constructor, that is, to have a constructor to access permissions, with public decoration, the parameters of the constructor to provide, that is, IClass can also parse, or error, the program injection method is as follows:

        public static void ConStructorCodeTest1 ()        {            Iunitycontainer container = new UnityContainer ();            Default registration (no naming), if there is a default registration later, overwrites the previous            container. Registertype<iclass, cbclass> ();            Container. Registertype<istudent, qlinstudent> ();            Resolves the default object            istudent Splitclass = container. Resolve<istudent> ();            Splitclass.showinfo ();        }

The configuration file is as follows:

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <configSections>    <section Name = "Unity" type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration "/>  </configSections>  <unity xmlns="/http Schemas.microsoft.com/practices/2010/unity ">    <!--Reference namespace-    <namespace name=" ConsoleApplication1.UnityDemo.Constructor "/>    <!--referencing assemblies--    <assembly name=" ConsoleApplication1 "/>    <!--containers--    <container name=" FirstClass ">      <!--mappings--      <register type= "IClass"  mapto= "Cbclass" ></register>      <register type= "IClass" Name= " EC "mapto=" Ecclass "></register>      <register type=" istudent "mapto=" Qlinstudent "  >      </register>    </container>  </unity></configuration>

The following is the load configuration file

        public static void ConStructorConfigTest1 ()        {            Iunitycontainer container = new UnityContainer ();            String configfile = "Http://www.cnblogs.com/UnityDemo/Constructor/Unity.config";            var filemap = new Execonfigurationfilemap {execonfigfilename = configfile};            To read configuration information from the config file, configure config            =                configurationmanager.openmappedexeconfiguration (filemap , configurationuserlevel.none);            Gets the configuration section of the specified name,            unityconfigurationsection, sections = (unityconfigurationsection) configuration. GetSection ("Unity");            Load the container node container named FirstClass            . Loadconfiguration (section, "FirstClass");            Istudent Splitclass = container. Resolve<istudent> ();            Splitclass.showinfo ();        }

2.2 Specifying constructors

If the constructor has more than one, it also initializes an object as shown above, and we can also display the Injectionconstructor attribute to specify a constructor to parse the object, as in the following declaration:

    public class Qlinstudent:istudent    {        private string Name {get; set;}        Private IClass Toclass {get; set;}        Public qlinstudent ()        {        }        [injectionconstructor] public        qlinstudent (IClass _class,string name)        {            toclass = _class;            name = name;        }        public void Showinfo ()        {            Console.WriteLine ("{0} enrolled in class: {1}", Name, Toclass.classname);}    }

2.3 Specify the registered name of the parameter dependency

The IClass parameter in the constructor, if Iunitycontainer is registered with more than one, the default is to use the one with no name, or by dependency depends on which name to specify which to register, code, the specified EC name is as follows:

        [Injectionconstructor]        Public Qlinstudent ([Dependency ("EC")]iclass _class)        {            toclass = _class;        }

The following registers a map named EC, if no name is called EC mapping will be an error

        public static void ConStructorCodeTest1 ()        {            Iunitycontainer container = new UnityContainer ();            Default registration (no naming), if there is a default registration later, overwrites the previous            container. Registertype<iclass, cbclass> ();            Name Registration            container. Registertype<iclass, ecclass> ("EC");            Container. Registertype<istudent, qlinstudent> ();            Resolves the default object            istudent Splitclass = container. Resolve<istudent> ();            Splitclass.showinfo ();        }

The configuration file mode, the code is not changed, the configuration to add a Name property on the line, as follows:

    <container name= "FirstClass" >      <!--mappings--      <register type= "IClass"  mapto= "Cbclass" > </register>      <register type= "IClass" name= "EC" mapto= "Ecclass" ></register>      <register Type= "istudent"  mapto= "qlinstudent" >      </register>    </container>

2.4 Specifying parameter values

The arguments in the constructor can also depend on a specified type value, and the following code relies on the Ecclass type, allowing the constructor to pass in a specific type, which is also the constructor argument, as follows:

        public static void ConStructorCodeTest1 ()        {            Iunitycontainer container = new UnityContainer ();            Default registration (no naming), if there is a default registration later, overwrites the previous            container. Registertype<iclass, cbclass> ();            Name Registration            container. Registertype<iclass, ecclass> ("EC");            Container. Registertype<istudent, qlinstudent> (New Injectionconstructor (New Cbclass ()));            Istudent Splitclass = container. Resolve<istudent> ();            Splitclass.showinfo ();        }

Or register an instance object, as follows:

        public static void ConStructorCodeTest1 ()        {            Iunitycontainer container = new UnityContainer ();            IClass Cbclass = new Cbclass {classname= "ITCSC class 051"};            Instance to register the named instance            container. Registerinstance<iclass> ("EC", Cbclass);            Container. Registertype<istudent, qlinstudent> ();            Istudent Splitclass = container. Resolve<istudent> ();            Splitclass.showinfo ();        }

The configuration file can also specify a type dependency, as follows, specifying ECCLASS:

      <register type= "istudent"  mapto= "qlinstudent" >        <constructor>          <param name= "_class" Type= "IClass" >            <dependency  type= "Ecclass"/>          </param>        </constructor>      </register>

The above has introduced the parameters, is using the Injectionconstructor type, now the constructor, one more parameter, as follows:

        [Injectionconstructor]        Public Qlinstudent ([Dependency ("EC")]iclass _class, string name)        {            toclass = _class;            name = name;        }

More than a name parameter, it must be provided for the container Iunitycontainer This parameter, without this raw material, it can not be constructed, it will be error, the following code:

        public static void ConStructorCodeTest1 ()        {            Iunitycontainer container = new UnityContainer ();            Container. Registertype<istudent, qlinstudent> (New Injectionconstructor (new Cbclass () {ClassName = "section 051"}, "Qlin"));            Istudent Splitclass = container. Resolve<istudent> ();            Splitclass.showinfo ();                   }

After injecting the parameters, it is also possible to overwrite the original parameters with the Parameteroverrides class at the next parse time, and change the parameter values as follows:

        public static void ConStructorCodeTest1 ()        {            Iunitycontainer container = new UnityContainer ();            Container. Registertype<istudent, qlinstudent> (New Injectionconstructor (new Cbclass () {ClassName = "section 051"}, "Qlin"));            istudent student = container. Resolve<istudent> ();            Student. Showinfo ();            Override parameter Resolution            istudent STUDENT1 = container. Resolve<istudent> (New Parameteroverrides ()                                                               {                                                                  {"_class", new Ecclass () {classname= "e-commerce 051"}},                                                                  {" Name "," LINQ "}                                                               });            Student1. Showinfo ();        }

3. Attribute Injection

is when the Unity container parses an object, assigns a value to the property, and has the operation permission to the public modifier property. Property injection is similar to constructor injection, just add a dependency attribute on the attribute that needs to be injected, dependency specify a registration name the name parameter is used to specify the names of the injected objects, and the attribute injection is injected with the initialization of the type, and is injected automatically at parse time. So the parsing is the same as before. The code modifies the following, adding the dependency attribute on the Toclass attribute to indicate that the attribute needs to be injected:

    public class Qlinstudent:istudent    {public        string Name {get; set;}        [Dependency ("EC")]        Public IClass Toclass {get; set;}        public void Showinfo ()        {            Console.WriteLine ("{0} enrolled in class: {1}", Name, Toclass.classname);}    }

The code is as follows:

            Iunitycontainer container = new UnityContainer ();            Container. Registertype<iclass, ecclass> ("EC");                     Container. Registertype<istudent, qlinstudent> ();            Istudent Splitclass = container. Resolve<istudent> ();            Splitclass.showinfo ();

Configuration file mode, depending on the <dependency name= "EC1" Name value can specify the name registered at the time of registration:

<unity xmlns= "Http://schemas.microsoft.com/practices/2010/unity" >    <!--Reference namespace-    < namespace name= "ConsoleApplication1.UnityDemo.Constructor4"/>    <!--referencing assemblies--    <assembly name= " ConsoleApplication1 "/>    <!--containers--    <container name=" FirstClass ">      <!--mappings--      <register type= "IClass"  mapto= "Cbclass" >            </register>      <register type= "IClass" Name= "EC1" mapto= "Ecclass" >        <property name= "ClassName" propertytype= "System.String" value= "e-commerce 051"/>      </register>      <register type= "istudent"  mapto= "qlinstudent" >        <property name= " Toclass ">          <dependency name=" EC1 "type=" Ecclass "/>        </property>      </register>    </container>  </unity>

Call:

4. Method injection

With the public modification method, the method injection is also similar to the constructor code to modify the following

    public class Qlinstudent:istudent    {public        string Name {get; set;}        Private IClass Toclass {get; set;}        [Injectionmethod]        public void Initclass (IClass _class)        {            toclass = _class;        }        public void Showinfo ()        {            Console.WriteLine ("{0} enrolled in class: {1}", Name, Toclass.classname);}    }

The programmatic injection is invariant, that is, when initializing, the injected value is as follows:

            Iunitycontainer container = new UnityContainer ();            Container. Registertype<iclass, ecclass> ();                     Container. Registertype<istudent, qlinstudent> ();            istudent student = container. Resolve<istudent> ();            Student. Showinfo ();

Configuration file Mode:

 <unity xmlns= "http://schemas.microsoft.com/practices/2010/unity" > <!--reference Namespaces-<namespace Nam E= "ConsoleApplication1.UnityDemo.Constructor5"/> <!--referencing assemblies-<assembly name= "ConsoleApplication1"/&G    T <!--containers--<container name= "FirstClass" > <!--Mapping relationships-<register type= "IClass" mapto= "CBCL The "> </register> <register type=" IClass "name=" EC1 "mapto=" Ecclass "> <property n  Ame= "ClassName" propertytype= "System.String" value= "e-commerce 051"/> </register> <register type= "Istudent"  mapto= "Qlinstudent" > <property name= "name" propertytype= "System.String" value= "Qlin"/> <method Name= "Initclass" > <param name= "_class" type= "IClass" > <dependency name= "EC1" type= "Ecclas S "/> </param> </method> </register> </container> </unity> 

5. Summary

Introduced 3 kinds of dependency injection methods, usually mainly used in such a few, and other complex like the expansion of containers, through this section, basically know the use of unity.

[IOC Container Unity] Third back: Dependency Injection

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.