[EntLib] Microsoft enterprise database 5.0 learning path-Step 10: Use Unity to decouple your system-PART2-learn how to use Unity (1)

Source: Internet
Author: User

Address: http://www.cnblogs.com/kyo-yo/archive/2010/11/01/Learning-EntLib-Tenth-Decoupling-Your-System-Using-The-Unity-PART2-Learn-To-Use-Unity-One.html

 

In the previous article, I briefly introduced some background knowledge about Unity, why should we use Unity, and what are the advantages of using Unity. We will continue to learn about Unity today, mainly to understand some common usage methods of Unity.

This article will mainly introduce:

Basic usage of UnityContainer in Unity, including common methods of the UnityContainer class, and several small examples are used to introduce specific usage methods, these examples are implemented in two ways: code and configuration files.

 

From the name of the UnityContainer (Unity container) class, we can see that it is the most important class of Unity. UnityContainer is like a headquarters of Unity, and objects are like soldiers, every soldier must use UnityContainer to manage the dependencies between all objects. All objects are created through the Unity container. It can also be said to be a foreign ministry, for our developers, we don't need to care about how internal implementation is implemented. We just need to set the relationship between objects in advance, and then tell UnityContainer what I need when necessary, unityContainer will send us what we need directly. (These metaphors may be incorrect, but they are the best one I can think)

Use code to achieve object Association Registration:

First, let's look at a simple example:

View sourceprint?
01 public interface IClass
02 {
03     void ShowInfo();
04 }
05 public class MyClass : IClass
06 {
07     public MyClass()
08     {
09  
10     }       
11  
12     public void ShowInfo()
13     {
14         Console.WriteLine("This is my class");
15     }
16 }
17 Specific call:
View sourceprint?
1 static void Main(string[] args)
2 {
3     IClass classInfo = new MyClass();
4     classInfo.ShowInfo();
5 }

This is the most common interface and its implementation class usage. It defines an interface and then defines a class to implement this interface. Then, in the specific process of use, the new Keyword can be used to instantiate the specific implementation interface. Although there is no syntax problem, this will cause tight coupling. If the specific implementation class changes, you need to modify the code, and if there are many similar codes, it will lead to changes to the entire project, or even exceptions, so we need to use IOC for decoupling. The specific code is as follows:

View sourceprint?
01 public static void ContainerCode()
02 {
03     IUnityContainer container = new UnityContainer();
04     container.RegisterType<IClass, MyClass>();
05     // Another registration method, but it is not convenient to use the RegisterType <> () method
06     //container.RegisterType(typeof(IClass), typeof(MyClass));
07     IClass classInfo = container.Resolve<IClass>();
08     // Another method to obtain a specific object through container
09     //IClass classInfo = container.Resolve(typeof(IClass));
10     classInfo.ShowInfo();
11 }

You can use Unity to manage the relationship between objects in the following steps:

1. Create an UnityContainer object.

2. Use the RegisterType method of the UnityContainer object to register the relationship between the object and the object.

3. Use the Resolve Method of the UnityContainer object to obtain the object associated with the specified object.

 

Use the configuration file to register object relations:

The above code is used to register the relationship between objects, but for a project, after the formal deployment, because the code is compiled into a DLL, if you want to modify the dependency, you need to modify the code and re-compile the Code. This is too troublesome. Therefore, Unity also provides the configuration file to configure the relationship between objects. The configuration is as follows:

View sourceprint?
01 <?xml version="1.0" encoding="utf-8" ?>
02 <configuration>
03   <configSections>
04     <section name="unity"
05              type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
06              Microsoft.Practices.Unity.Configuration"/>
07   </configSections>
08   <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
09     <alias alias="IClass" type="UnityStudyConsole.IDemo.IClass, UnityStudyConsole" />
10     <alias alias="MyClass" type="UnityStudyConsole.Demo.MyClass, UnityStudyConsole" />
11      
12     <container>
13       <register type="IClass" name="ConfigClass" mapTo="MyClass" />
14     </container>
15   </unity>
16 </configuration>

The code is called as follows:

View sourceprint?
01 public static void ContainerConfiguration()
02 {
03     IUnityContainer container = new UnityContainer();
04     // Get the configuration section with the specified name
05     UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
06     // The default method. By default, the configuration information under the "unity" configuration section is obtained.
07     container.LoadConfiguration();
08     // Obtain the configuration information under the named configuration section <container name = "FirstClass">
09     container.LoadConfiguration("FirstClass");
10     // Obtain the configuration information in a specific configuration section
11     container.LoadConfiguration(section);
12     // Obtain the configuration information in the named configuration section <container name = "FirstClass"> under a specific configuration section.
13     container.LoadConfiguration(section, "FirstClass");
14  
15     IClass classInfo = container.Resolve<IClass>("ConfigClass");
16     classInfo.ShowInfo();
17 }

To configure the Unity information through the configuration file, follow these steps:

1. Register unity in the <configSections> Configuration section of the configuration file.

2. Add Unity configuration information in the <configuration> configuration section.

3. Read the configuration information in the Code and load the configuration into the UnityContainer.

The configuration file can be used to configure object information. Although the dependency between objects can be changed during deployment, if the system is too complex, the configuration file will increase, therefore, we need to extract the Unity configuration information from the App. config or web. config is separated, but the method called in the previous code is invalid. Now we need to modify the existing code:

View sourceprint?
01 public static void ContainerConfigurationFromFile(string configFile)
02 {
03     // Obtain the specified config File Based on the file name
04     var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
05     // Read the configuration information from the config file
06     Configuration configuration =
07         ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
08     var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
09  
10     var container = new UnityContainer()
11         .LoadConfiguration(unitySection, "FirstClass");
12  
13     IClass classInfo = container.Resolve<IClass>("ConfigClass");
14     classInfo.ShowInfo();
15 }

Since the Unity configuration is relatively complex, it is difficult to get started at once, and unlike other modules in the Enterprise Library, the configuration tool can be used for configuration. Therefore, the p & p team can configure Unity through the configuration file for convenience, unityconfigurationconfigurationconfigurationconfigurxsd has been built in the installation package of Enterprise Library 5.0. You can find it under X: \ Program Files \ Microsoft Visual Studio X.0 \ Xml \ Schemas, in this way, you can only prompt When configuring Unity in the configuration file, such:

Note that if you want to see this prompt, you need to add an xmlnsHttp://schemas.microsoft.com/practices/2010/unity. (If EntLib5 is not installed, so there is no unityconfigurationconfigurationconfigurxsd, you can find this xsd in the following sample code .)

 

The above is all the content in this article. It mainly introduces the basic usage of UnityContainer-how to implement the relationship between objects through code and configuration files. If you have any questions, please kindly advise!

 

Download Sample Code: Click here to download

 

Index of a series of articles on the learning path of Microsoft enterprise database 5.0:

Step 1: getting started

Step 2: Use the VS2010 + Data Access module to create a multi-database project

Step 3: Add exception handling to the project (record to the database using custom extension)

Step 4: Use the cache to improve the website's performance (EntLib Caching)

Step 5: Introduce the EntLib. Validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1

Step 5: Introduce the EntLib. Validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1

Step 5: Introduce the EntLib. Validation module information, the implementation level of the validators, and the use of various built-in validators-Part 2

Step 6: Use the Validation module for server-side data verification

Step 7: Simple Analysis of the Cryptographer encryption module, custom encryption interfaces, and usage-Part 1

Step 7: Simple Analysis of the Cryptographer encryption module, custom encryption interfaces, and usage-Part 2

Step 8. Use the Configuration Setting module and other methods to classify and manage enterprise database Configuration information

Step 9: Use the PolicyInjection module for AOP-PART1-basic usage

Step 9: Use the PolicyInjection module for AOP-PART2-custom Matching Rule

Step 9: Use the PolicyInjection module for AOP-PART3 -- Introduction to built-in Call Handler

Step 9: Use the PolicyInjection module for AOP-PART4 -- create a custom Call Handler to achieve user operation Logging

Step 10: Use Unity to decouple your system-PART1-Why use Unity?

Step 10: Use Unity to decouple your system-PART2-learn how to use Unity (1)

Extended learning:

Extended learning and dependency injection in libraries (rebuilding Microsoft Enterprise Library) [go]

 

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.