Microsoft Enterprise Library 5.0 series (8) Unity Dependency Injection and Interception

Source: Internet
Author: User
Tags ip number
Dependency injection container Unity:

The structure of Unity is similar to the IOC (control inversion or dependency injection) container in Castle. We use abstract interfaces to isolate the dependencies between users and specific implementations, but no matter how abstract, finally, we need to create an instance of a specific implementation class. This kind of instance object that creates a specific implementation class will result in dependencies on the specific implementation. In order to eliminate this dependency, the dependency needs to be removed from the outside of the program (such as the configuration file ). After dependency injection is used, these classes are completely written based on abstract interfaces, so they can adapt to the changes as much as possible. There are three forms of dependency Injection: Constructor Injection, Setter Injection, and Interface Injection ).

As before, let's use the actual requirements to demonstrate the actual problems that can be solved by this module (The following example is a copy of TerryLee's article: Quick Start To the Castle IOC container, here I use Unity to restore the site and demonstrate how to solve the same problem with Unity ):

Now, if we have such a requirement, we can develop a log component to output the log information to a text file and format the output information to implement it with schematic code.


1. Create a new console application, add the required Dll file, and add the required reference:

 

Add reference:

Using Microsoft. Practices. Unity;

2. test:

 

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using Microsoft. Practices. Unity;

Namespace test
{
Class Program
{
Static void Main (string [] args)
{
Console. WriteLine ("Test 1 :");
Test1 ();

Console. WriteLine ("Test 2 :");
Test2 ();
}

Private static void test1 ()
{
// 1. Log formatting is only a component in Log service. (Note: It doesn't make much sense to instantiate this component here. The only use is to provide a parameter for the service)
ILogFormatter logFormatter = new TextFormatter ("/");

// 2. Create a service
ILog logServer = new TextFileLog (@ "C: \ test. log", logFormatter );

// 3. Use the service
LogServer. Write ("log body ");
}

Private static void test2 ()
{
// 1. Register a container;
IUnityContainer container = new UnityContainer ();

// 2. register the ILog service with the container and notify the container to use TextFileLog to implement the service.
Container. RegisterType <ILog, TextFileLog> ();

// 3. Register ILogFormatter with the container and notify the container to implement it using TextFormatter
// Another Target parameter is required for the constructor of the container Discovery class. This parameter is injected with InjectionProperty.
Container
. RegisterType <ILogFormatter, TextFormatter> (new InjectionProperty ("Target ","/"))
. RegisterInstance <string> (@ "C: \ test. log ");

// 4. Get the service
ILog log = container. Resolve <ILog> ();

// 5. Use the service. So far, we have not used the new keyword to create an instance of a specific class,
// It completely shields the instantiation of components and services, and is automatically assembled by Unity, making the program more flexible.
Log. Write ("log body ");
}
}

}

 

Running result:

 

 

So far, we need to learn a few knowledge points:

1. Service

A service is an interface. An interface defines a service, so that the implementation of a replacement service has no impact on the code used for the interface service. Like the ILog in the above example, ILogFormatter is a service. In this example, we support the log records of a text file. If you want to implement the log records recorded by the database, all must comply with the ILog interface.

2. Components

Simply put, a component is a reusable Program unit. It implements an interface and only implements this good interface. That is to say, a component is a class that implements a service interface. In the preceding example, TextFileLog and TextFormatter are all components.

3. Automatic Assembly

In the above example, we may have noticed that TextFileLog depends on TextFormatter, but we didn't specify dependencies between them in the configuration file. This is a smart place for Castle IOC, it can automatically manage dependencies between components without the need to write specific xml config for configuration, that is, the meaning of automatic assembly.

 

Here is an introduction to IOC copied from other websites, which is vivid and helpful for your understanding:

IoC (Inversion of Control) also exists in the Spring framework ). And is the core of spring. For the spring framework, the so-called IoC is that spring is responsible for controlling the relationship between object lifecycles and objects. What does this mean? For example, how do we find a girlfriend? The common situation is that we go around to see where there is a beautiful and good mm, and then inquire about their interests, QQ number, phone number, ip number, iq number ........., Find a way to get to know them and give them what they want ...... This process is complex and profound, and we must design and face each link on our own. This is also true for program development of data transfer. To use another object in an object, you must obtain it (new by yourself or query one from JNDI ), after use, the object will be destroyed (such as Connection), and the object will always be combined with other interfaces or classes.
How does IoC work? It's a bit like finding a girlfriend through a matchmaking agency. I introduced a third party between my girlfriend and me: the marriage agency. The matchmaking agency manages a lot of information about men and women. I can submit a list to the matchmaking agency to tell it what kind of girlfriend I want to find, such as Li jiaxin, Lin xilei, and Jay Chou, the speed is like Carlos, the technology is like Zidane, and then the matchmaking agency will provide a mm according to our requirements. We just need to get in love with her and get married. It is simple and clear. If the person selected by the matchmaking agency does not meet the requirements, we will throw an exception. The entire process is no longer controlled by myself, but controlled by a mechanism similar to a container such as matchmaking agency. This is the development method advocated by Spring. All classes will be registered in the spring container to tell spring what you are and what you need, then spring will take the initiative to give you what you want when the system runs properly, and also give you something else you need. The creation and destruction of all classes are controlled by spring. That is to say, the object lifecycle is not referenced but spring. For a specific object, it used to control other objects. Now all objects are controlled by spring, so this is called control inversion.

 

 Download the sample program in this article:

(> '[]')> Click to download <('[]' <)

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.