Overview
Unity is a lightweight and scalable dependency injection container that supports constructor, attribute, and method call injection. Unity can handle problems faced by developers engaged in component-based software engineering. Build a successful applicationProgramThe key is to implement a very loose coupling design. Apps with loose coupling are more flexible and easy to maintain. Such programs are easier to test during development. You can simulate objects with strong dependencies (lightweight Simulation Implementation), such as database connection, network connection, ERP connection, and rich user interface components. For example, objects that process customer information may rely on data storage accessed by other objects, verify information, and check whether the user is authorized to perform updates. The dependency Injection Technology ensures that the customer class correctly instantiates and fills all these objects, especially when dependency may be abstract.
Complete unity configuration file format
<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <configsections> <section name = "Unity" type = "Microsoft. practices. unity. configuration. unityconfigurationsection, Microsoft. practices. unity. configuration, version = 1.0.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35 "/> </configsections> <unity> <typealiases> <typealias alias =" Singleton "type =" Microsoft. practices. unity. containercontrolledlifetimemanager, Microsoft. practices. unity "/> <typealias alias =" external "type =" Microsoft. practices. unity. externallycontrolledlifetimemanager, Microsoft. practices. unity "/> <typealias alias =" imyinterface "type =" myapplication. mytypes. myinterface, myapplication. mytypes "/> <typealias alias =" myrealobject "type =" myapplication. mytypes. myrealobject, myapplication. mytypes "/> <typealias alias =" imyservice "type =" myapplication. mytypes. myservice, myapplication. mytypes "/> <typealias alias =" mydataservice "type =" myapplication. mytypes. mydataservice, myapplication. mytypes "/> <typealias alias =" mycustomlifetime "type =" myapplication. mylifetimemanager, myapplication. mytypes "/> </typealiases> <containers> <container name =" containerone "> <types> <type =" custom. mybaseclass "mapto =" custom. myconcreteclass "/> <type =" imyinterface "mapto =" myrealobject "name =" mymapping "/> <type =" custom. mybaseclass "mapto =" custom. myconcreteclass "> <lifetime type =" Singleton "/> </type> <type =" imyinterface "mapto =" myrealobject "name =" realobject "> <lifetime type =" external "/> </type> <type =" custom. mybaseclass "mapto =" custom. myconcreteclass "> <lifetime value =" sessionkey "type =" myapplication. mytypes. mylifetimemanager, myapplication. mytypes "/> </type> <type =" imyinterface "mapto =" myrealobject "name =" customsession "> <lifetime type =" mycustomlifetime "value =" reversekey "typeconverter = "myapplication. mytypes. mytypeconverter, myapplication. mytypes "/> </type> <type =" imyservice "mapto =" mydataservice "name =" dataservice "> <typeconfig extensiontype =" Microsoft. practices. unity. configuration. typeinjectionelement, Microsoft. practices. unity. configuration "> <constructor> <Param name =" connectionstring "parametertype =" string "> <value =" adventureworks "/> </param> <Param name =" logger "parametertype = "ilogger"> <dependency/> </param> (vehicle extension) </constructor> <property name = "logger" propertytype = "ilogger"/> <method name = "initialize"> <Param name = "connectionstring" parametertype = "string"> <value value = "contoso"/> </param> <Param name = "dataservice" parametertype = "imyservice"> <dependency/> </param> </method> </typeconfig> </type> </types> <instances> <Add name = "myinstance1" type = "system. string "value =" some value "/> <Add name =" myinstance2 "type =" system. datetime "value =" 2008-02-05t17: 50: 00 "/> </instances> <extensions> <add type =" MyApp. myextensions. specialone "/> </extensions> <extensionconfig> <Add name =" myextensionconfighandler "type =" MyApp. myextensions. specialone. confighandler "/> </extensionconfig> </container> </containers> </Unity> </configuration>
Unity Design Drawing
The configuration section of unity is named "Unity". The type of the section handler is Microsoft. Practices. Unity. configuration. unityconfigurationsection, which is included in the Assembly Microsoft. Practices. Unity. configuration. A reference to the Assembly should be added to the website.
The child element of Unity contains a containers element. The containers element can contain several container elements. The container element is the configuration of each container. It has an optional name attribute to specify the container name.
<Types> an element is one of the sub-elements of the iner element. Contains any number of type elements to add type registration. These configurations are registered by container. registertype <tfrom, plugin>;
The attribute of the type element.
Name: the name used when registering this type. This attribute is optional. If this attribute is not specified, the add element is the default type ing.
Type: The Source Type configured in the container. If this is ing registration, this is the type of the starting object of the ing; if this is a single-piece registration, this is the type of the object. This attribute is required.
Mapto: Target type of Type ing. If this is ing registration, this is the type of the mapped target object. This attribute is optional.
Lifetime: Set the lifecycle of a given type and name. Is a value from the lifetimestyle enumeration. The valid value is transient (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 both the type and mapto attributes are specified when a single piece is configured, The setsingleton method returns the type specified in the mapto attribute. If no value is specified for the mapto attribute, the setsingleton method returns the type specified in the type attribute.
The <instances> element maintains the list of existing object instances used for this container. These objects are registered using the registerinstance method of the container.The instances element contains a series of add elements for adding a single instance.
Attribute of the add element.
Name: the name used to register this instance. This attribute is optional.
Type: Type of the instance. This attribute is optional. If this parameter is ignored, it is assumed that the type is system. String.
Value: the value used to initialize the instance. This attribute is required.
Typeconverter: type converter used to convert the provided value to the matching type of the instance. If not specified, the default converter of the specified type is used. This attribute is optional.
<Typeconfig extensiontype = "Microsoft. Practices. Unity. configuration. typeinjectionelement, Microsoft. Practices. Unity. Configuration">
This parameter is used to configure object initialization information for Constructor dependency injection, property dependency injection, and method dependency injection during type registration.It contains the following sub-elements:
<Constructor> <Param name = "connectionstring" parametertype = "string"> <value = "adventureworks"/> </param> <Param name = "logger" parametertype = "ilogger "> <dependency/> </param> </constructor> <property name =" logger "propertytype =" ilogger "/> <method name =" initialize "> <Param name = "connectionstring" parametertype = "string"> <value = "contoso"/> </param> <Param name = "dataservice" parametertype = "imyservice"> <dependency/> </param> </method>
When Container. Resolve () is executed to generate an object instance, the object to be generated is injected with dependency according to the configuration information above.
Ii. load configuration information to the container
1. Load a separate unnamed container or specify the default container:
Iunitycontainer Container = new unitycontainer ();
Unityconfigurationsection section = (unityconfigurationsection) configurationmanager. getsection ("Unity ");
Section. containers. Default. Configure (container );
In this way, the type ing is registered in the unitycontainer container according to the configuration information in the configuration file.
2. to load the configuration information of a special named container, use the container name defined in the configuration file instead of referencing the default container.For example, if there is a container named containerone in the configuration, you can use the followingCodeInitialize and load it:
Iunitycontainer Container = new unitycontainer ();
Unityconfigurationsection section = (unityconfigurationsection) configurationmanager. getsection ("Unity ");
Section. containers ["containerone"]. Configure (container );
3. To create a nested container inheritance from the configuration information, you can simply use the createchildcontainer method to create a container object in the inheritance depth you need, then load the appropriate configurations by reading their respective configuration files.The following code instantiates and loads two containers from the configuration file. The configuration file also contains registration information, type ing, and extended definitions for the two containers named containerone and newstedchildcontainer.
Iunitycontainer parentcontainer = new unitycontainer ();
Iunitycontainer childcontainer = parentcontainer. createchildcontainer ();
Unityconfigurationsection section = (unityconfigurationsection) configurationmanager. getsection ("Unity ");
Section. containers ["containerone"]. getconfigcommand (). Configure (parentcontainer );
Section. containers ["nestedchildcontainer"]. Configure (childcontainer );
API
Unitycontainer. registertype <itfrom, Region> ();
Unitycontainer. registertype <itfrom, Region> ();
Unitycontainer. registertype <itfrom, Region> ("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 ();
Example
Public abstract class sqlhelp {public abstract string sqlconnection ();} public class mysqlhelp: sqlhelp {public override string sqlconnection () {return "My SQL connection" ;}} public class mssqlhelp: sqlhelp {public override string sqlconnection () {return "ms SQL connection" ;}} public class oraclesqlhelp: sqlhelp {public override string sqlconnection () {return "Oracle SQL connection ";}}
App. config Configuration
<? 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 =" sqlhelp, new_code "mapto =" mysqlhelp, new_code "> <lifetime type =" Singleton "/> </register> </container> </Unity> </configuration>
Implementation Code
Public void main () {iunitycontainer Container = new unitycontainer (); unityconfigurationsection section = (unityconfigurationsection) configurationmanager. getsection ("Unity"); section. containers. default. configure (container); sqlhelp = container. resolve <sqlhelp> (); console. writeline (sqlhelp. sqlconnection ());}
Running result:
My SQL connection
You are welcome to participate in the discussion. If you find it helpful, please clickRecommended. Thank you very much.
Author: Spring Yang
Source: http://www.cnblogs.com/springyangwc/
the copyright of this article is shared by the author and the blog. You are welcome to reprint it. However, you must keep this statement without the consent of the author, the connection to the original text is clearly displayed on the Article page. Otherwise, the legal liability is reserved.