Net Unity IOC Injection summary

Source: Internet
Author: User

Brief introduction

The Unity Application Block (Unity) is a lightweight, extensible dependency injection container that supports constructors, properties, and method invocation injection. It provides developers with the following benefits:


simplifies the creation of objects, especially hierarchical object structures and dependencies.


Allows developers to specify dependent demand abstractions at run time or configuration, and simplifies management of crosscutting concerns.


The service locator feature allows client code to save or cache containers. This is especially useful in ASP. NET WEB applications where developers can persist containers to ASP. NET Session or application.


Configuration files (1) Simple Register method

<?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" >

<container>

<!--register Type= "full class Name,namespace"-

<register type= "Unitytest.isqlhelper,unitytest" mapto= "Unitytest.mysqlhelper,unitytest" >

<lifetime type= "Singleton"/>

</register>

</container>

</unity>

</configuration>


Configuration file (2) alias mode

<configSections>

<!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468--

<section name= "EntityFramework" type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=5.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089 "requirePermission=" false "/>

<section name= "Unity"

Type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,

Microsoft.Practices.Unity.Configuration, version=2.1.505.0,

Culture=neutral, publickeytoken=31bf3856ad364e35 "/>

</configSections>

<unity>

<typeAliases>

<!--life cycle Manager Type--

<typealias alias= "Singleton"

Type= "Microsoft.Practices.Unity.ContainerControlledLifetimeManager,

Microsoft.Practices.Unity "/>

<typealias alias= "external"

Type= "Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,

Microsoft.Practices.Unity "/>


<!--custom object Types--

<!--typealias node is an alias for the type (alias)--

<typealias alias= "IMyInterface"

Type= "Myobjects.imyinterface, myobjects"/>

<typealias alias= "Myrealobject"

Type= "Myobjects.myrealobject, myobjects"/>

<typealias alias= "Myotherobject"

Type= "Myobjects.myotherobject, myobjects"/>

<typealias alias= "ILogger"

Type= "Myobjects.ilogger, myobjects"/>

<typealias alias= "MyLogger"

Type= "Myobjects.mylogger, myobjects"/>

<typealias alias= "Myfastlogger"

Type= "Myobjects.myfastlogger, myobjects"/>

</typeAliases>


<containers>

<!--container node defines a container for managing dependencies and lifecycles--

<container name= "Containerone" >

<types>

<!--types provides specific definitions of dependencies and lifecycles--

<!--Default (un-named) mapping for IMyInterface to Myrealobject-->

<type type= "IMyInterface" mapto= "Myrealobject"/>

<!--Default (un-named) mapping for ILogger to MyLogger-

<type type= "ILogger" mapto= "MyLogger" >

<lifetime type= "Singleton"/>

</type>

<!--Named mapping for ILogger to MyLogger-

<type type= "ILogger" mapto= "MyLogger" name= "Standardlogger" >

<lifetime type= "Singleton"/>

</type>

<!--Named mapping for ILogger to Myfastlogger-

<type type= "ILogger" mapto= "Myfastlogger" name= "Superfastlogger" >

<lifetime type= "external"/>

</type>


</types>


</container>


</containers>


</unity>


Configuration files (3) namespace mode

<?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 Namespaces-

<namespace name= "ConsoleApplication1.UnityDemo.Constructor"/>

<!--referencing assemblies-

<assembly name= "ConsoleApplication1"/>

<!--Containers--

<container name= "FirstClass" >

<!--mapping Relationships--

<register type= "IClass" mapto= "Cbclass" ></register>

<register type= "IClass" name= "EC" mapto= "Ecclass" ></register>

<register type= "istudent" mapto= "Qlinstudent" >


</register>

</container>

</unity>

</configuration>



Node description

Unity is configured under the Unity node


Typealiases is a configuration type alias, the type configured in Typealiases can be used directly in Contaniners, when used in containers


You do not need to fill out the complete type, just fill in the typealiases registered alias. Of course, you can also register the complete type directly in the container.


Alias is the name of the Typealias, type is.


The Containners node can contain multiple container, and multiple container can be nested in one container.


Name: Names to use when registering this type. This property is optional, and if you do not specify this property, the add element is the default type mapping.

Type: The source types that are configured in the container. If this is a mapping registration, this is the type of the starting object for the mapping, and if this is a single-piece registration, this is the type of object. This property is required.

Mapto: The target type of the type mapping. If this is a mapping registration, this is the type of target object that is mapped. This property is optional.

Lifetime: Sets the life cycle for the given type and name. is a value from the Lifetimestyle enumeration. The valid value is Transient (the default), which causes the container to create a new instance each time, and Singleton, which causes the container to return the same instance for each request. If you specify both the type and the Mapto property when you configure a single piece, the Setsingleton method returns the types specified in the Mapto property. If the Mapto property does not specify a value, the Setsingleton method returns the type specified in the Type property.


Note: The current (Vs2012) Unity version=2.1.505.0


<section name= "Unity"


Type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,


Microsoft.Practices.Unity.Configuration, version=2.1.505.0,


Culture=neutral, publickeytoken=31bf3856ad364e35 "/>



Constructor injection

More than one constructor, which defaults to the maximum number of parameters, or specifies a constructor using [Injectionconstructor]


Constructor Pass parameters

Iunitycontainer container = new UnityContainer ();

IClass Cbclass = new Cbclass {classname= "ITCSC class 051"};

Instance registering a named instance

Container. Registerinstance<iclass> ("EC", Cbclass);

Container. Registertype<istudent, qlinstudent> ();

Istudent Splitclass = container. Resolve<istudent> ();

Splitclass.showinfo ();


[Injectionconstructor]

Public Qlinstudent ([Dependency ("EC")]iclass _class, string name)

{

Toclass = _class;

name = name;

}


<register type= "istudent" mapto= "Qlinstudent" >

<constructor>

<param name= "_class" type= "IClass" >

<dependency type= "Ecclass"/>

</param>

</constructor>

</register>



Parametric replication

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 ();


Construction parameter pass-through value (no configuration required, direct value transfer)

Object parameters

Irequest r=unityhelper.getunity (). Resolve<irequest> (New Parameteroverrides () {"Model", New model () {name= "dragon", pass= "World"}});

Model model = Unityhelper.getunity (). Resolve<model> ();

return r.getrequest () + "service name";


object and Normal type parameters

Irequest r = unityhelper.getunity (). Resolve<irequest> (New Parameteroverrides () {"Model", New model () {Name = "dragon", Pass = "World"}}, {"Test", "testing"});



attribute injection (Assigning a value to a property)

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 Namespaces-

<namespace name= "ConsoleApplication1.UnityDemo.Constructor4"/>

<!--referencing assemblies-

<assembly name= "ConsoleApplication1"/>

<!--Containers--

<container name= "FirstClass" >

<!--mapping Relationships--

<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>



Method injection

<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= "Ecclass"/>

</param>

</method>

</register>


Net Unity IOC Injection summary

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.