Configuration and call of the web. config file in Unity

Source: Internet
Author: User

In the previous articleArticle"Unit simple dependency injection", we can achieve loose coupling between the constructed object and the dependent object, so that our abstraction layer (player) can be stable, however, the customer class and the player class are not completely decoupled, that is, when we do not want to use mp3player injection, but want to use cdplayer injection, we need to modify the container registration of the customer class. Below we use the web. config configuration file to solve this problem.
Unity ApplicationProgramYou can read the configuration information from the xml configuration file. The configuration file can be app. config of the Windows Forms Application or web. config of the ASP. NET application. Of course, you can also load configuration information from any other XML format file or other data sources.

In this article, we will study the format and configuration reading of the Unity configuration file, and illustrate how to obtain the instance through examples.
1. 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> (CHE Yanlu)
</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>
</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>
Structure diagram:

Why is it so complicated to see many of the above content? In fact, the above content is a complete structure for reference. It is generally not used in daily development. The most used element mark here is: <type> label in <container> <containers>.

The configuration section of unity is named "Unity", and the type of the section handler is Microsoft. practices. unity. configuration. unityconfigurationsection, which is included in the program set 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 );

3. generate an object instance from the container ing information:
The resolve method of the unitycontainer class is still used here. I will not talk about it here.

4. A simple example:
1. Class Structure:
Public abstract class player
{
Public abstract string play ();
}
Public class mp3player: Player
{
Public override string play ()
{
Return ("This Is A mp3player ");
}
}
Public class cdplayer: Player
{
Public override string play ()
{
Return ("This Is A cdplayer ");
}
}
Public class dvdplayer: Player
{
Public override string play ()
{
Return ("This Is A dvdplayer ");
}
}

2. Web. config file configuration
<Configsections>
<Section name = "Unity" type = "Microsoft. Practices. Unity. configuration. unityconfigurationsection, Microsoft. Practices. Unity. Configuration"/>
</Configsections>
<Unity>
<Containers>
<Container>
<Types>
<Type = "player, app_code" mapto = "mp3player, app_code"> </type>
</Types>
</Container>
</Containers>
</Unity>
(CHE Yanlu)
3. Implementation of Customer Code:
Iunitycontainer Container = new unitycontainer ();
Unityconfigurationsection section = (unityconfigurationsection) configurationmanager. getsection ("Unity ");
Section. containers. Default. Configure (container );

Player P = container. Resolve <player> ();
Response. Write (P. Play ());

4. Running result:

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.