[Entlib] Microsoft enterprise database 5.0 learning path-Step 10: Use unity to decouple your system-Part3-dependency Injection

Source: Internet
Author: User

Continue to learn about unity. In the previous articles, we have made a detailed introduction to how to use unity.CodeAnd the configuration file to register the relationship between objects, the use of all built-in life cycle management in unity, and some advanced applications of Unity's register and resolve. Through Part1 -- why use unity? We know that unity can help us simplify and manage the relationships between objects (that is, the relationships described in previous articles ), today, we will introduce another important feature of unity-di (dependency injection ).

This articleArticleWe will mainly introduce:

1. constructor injection.

2. Property injection.

3. Method injection.

4. Use the configuration to complete various injections.

5. Inject the created object.

 

1. constructor Injection

In some cases, the constructor in the class we write will include references to other objects, as shown in the following code:

 
Public subject2 (myclass myclass1, myclass myclass2) {myclass1.name = "Class 1"; myclass2.name = "Class 2 ";}

We can see that this constructor has two parameters, all of which depend on the myclass class. If we want to call them normally, we always need to construct two myclass objects, so it is relatively troublesome, however, using unity for calling is much more convenient., The following code:

 
Container. Resolve <subject2> ();

Only one line is acceptable. The unity container will automatically help us build the desired dependent object instance.

Of course, this is simple to use. In actual situations, we will not write code like this. Instead, we will not directly reference the object, but directly reference the interface. This can eliminate code coupling., The following code:

 
Public subject2 (iclass myclass1) {myclass1.name = "Class 1 ";}

In this way, the constructor of the subject2 class only depends on the iclass interface and the specific implementation class. In this case, if you want to call the subject2 class, you need to register the relationship between objects, the following code:

 
Public static void constructorinjection () {// container. Resolve <subject2> (); container. registertype <iclass, myclass> (); container. Resolve <subject2> ();}

When you get an object through the Unity container object, the default registration object is always obtained by default,But what if I want to specify a specific object when calling the subject2 constructor parameter?

In this case, we need to use the dependency feature class to solve the problem. We need to add the dependency feature to the dependency parameters that need to be specially specified, specify the parameter name for dependency (this parameter indicates the name specified when the object relationship is registered). The Code is as follows:

 
Public subject2 ([dependency ("your")] iclass classinfo) {classinfo. Name = "Class 1 ";}

Call code:

 
Container. registertype <iclass, myclass> (). registertype <iclass, yourclass> ("your"); container. Resolve <subject2> ();

As you can see, I registered two objects for iclass, and I used the dependency feature on subject2's constructor parameter to specify the classinfo parameter to get the object registered with the "your" name.

 

Another problem is that when a class has multiple constructor functions, how do we distinguish which constructor needs to implement injection and which one does not?

In this case, the injectionconstructor feature can be used for identification. The Code is as follows:

[Injectionconstructor] public subject2 ([dependency ("your")] iclass classinfo) {classinfo. name = "Class 1";} public subject2 (iclass classinfo1, iclass classinfo2) {classinfo1.name = "Class 1"; classinfo2.name = "Class 2 ";}

Unity only calls the constructor that identifies the injectionconstructor feature, which can be called by unity if multiple constructor features are used.

 

Ii. Property Injection

Property injection is similar to constructor injection. You only need to add a dependency attribute to the property to be injected. You can also specify a name parameter for dependency to specify the specific object of the injection attribute, the following code adds the dependency feature on the subject attribute to indicate that this attribute needs to be injected:

Public class myclass: iclass {public myclass () {} public void showinfo () {console. writeline ("this is my class");} [dependency ("subject1")] public isubject subject {Get; set;} public string name {Get; set ;} public String description {Get; Set ;}}

Specific call code:

 
Public static void propertyinjection () {container. registertype <isubject, subject1> ("subject1 "). registertype <iclass, myclass> (); var classinfo = container. resolve <iclass> (); console. writeline (classinfo. subject. name );}

In this way, the subject attribute of classinfo is automatically associated with the subject1 class (the property injection is completed), and "Subject 1" can be obtained by accessing classinfo. Subject. Name ".

 

Iii. Method Injection

method injection only needs to add a feature to the method to be injected-injectionmethod ( its usage method is similar to the construction injection method ), in this way, unity will automatically help us complete the injection. The method injection is the same as the construction injection. You can also specify the dependency attribute on the method parameters to specify the registration that the parameter depends on, the following class code contains constructor injection, property injection, and method injection. This class is more intuitive to show together:

Public class myclass: iclass {public myclass () {} public myclass (isubject subjectinfo) {This. tempsubject1 = subjectinfo;} public void showinfo () {console. writeline ("temporary account 1 name after successful constructor injection:" + this. tempsubject1.name); console. writeline ("temporary account name after successful property injection:" + this. subject. name); console. writeline ("temporary account 2 name after method injection is successful:" + this. tempsubject2.name);} [injectionmethod] public void Init (isubject subjectinfo) {tempsubject2 = subjectinfo;} [dependency ("subject1")] public isubject subject {Get; set ;} public isubject tempsubject1 {Get; set;} public isubject tempsubject2 {Get; set;} public string name {Get; set;} Public String description {Get; set ;}}

Specific call code:

Public static void methodinjection () {container. registertype <isubject, subject3> ("subject1 "). registertype <isubject, subject4> (); container. registertype <iclass, myclass> (); var classinfo = container. resolve <iclass> (); classinfo. showinfo ();}

As follows:

 

4. Use configuration to complete various injections

The Code demonstrated above is to inject objects through code. The following shows how to configure the injection through the configuration file. The specific configuration code is as follows:

<! -- Dependency injection configuration, including construction injection, method injection, and property injection --> <alias = "iclass" type = "unitystudyconsole. idemo. iclass, unitystudyconsole "/> <alias =" myclass "type =" unitystudyconsole. demo. myclass, unitystudyconsole "/> <alias =" isubject "type =" unitystudyconsole. idemo. isubject, unitystudyconsole "/> <alias =" subject3 "type =" unitystudyconsole. demo. subject3, unitystudyconsole "/> <alias =" subject4 "type =" unitystudyconsole. demo. subject4, unitystudyconsole "/> <container name =" third "> <register type =" iclass "mapto =" myclass "> <constructor> <Param name =" subjectinfo "type =" isubject"> <dependency name = "subjectinfo" type = "subject4"/> </param> </constructor> <method name = "init"> <Param name = "subjectinfo" type = "isubject"> <dependency name = "subjectinfo" type = "subject4"/> </param> </method> <property name = "subject"> <dependency name = "subject1 "type =" subject3 "/> </property> </register> </container>

The Code is as follows:

 
Public static void diconfiguration () {// obtain the configuration information container under the named configuration section <container name = "third"> in the specific configuration section. loadconfiguration ("third"); var classinfo = container. resolve <iclass> (); classinfo. showinfo ();}

The specific effect is the same as above, but the dependency injection here is implemented through the configuration file.

 

5. Inject the created object

In general, if you want to implement dependency injection, you need to register the object through the Unity container and then get the object through the Unity container, but if the object already exists (that is, the object is not obtained through the Unity container ), in this case, how can we use unity to implement dependency injection on existing objects?

The Unity container has provided us with a solution to this situation, namely the buildup method. You can see the following code:

Public static void buildup () {// register the relationship between isubject and mysubject in advance // specify a name to facilitate the application of [dependency ("subject1")] on the attributes of the interface features // For details, see idemo. iclass container. registertype <isubject, subject1> ("subject1"); iclass classinfo = new myclass (); iclass classinfo2 = container. buildup <iclass> (classinfo); console. writeline (classinfo2.subject. name) ;}# endregion

In the above Code, an object instance has been created. In this case, you only need to put this object as a parameter in buildup, and you also need to specify the interface or parent class type implemented by this object instance, in this way, unity will automatically help us inject various existing object instances.

Note that, unlike the three dependency injection methods mentioned above, dependency injection in the preceding three methods must use injectionconstructor, injectionmethoddependency, and features in a specific class, if dependency injection is performed on an existing object, you need to write injectionconstructor, injectionmethod, and dependency in the interface or parent class implemented by this object instance. Otherwise, an error is reported!

 

As of this article, various common functions of unity have been introduced. You can download the followingSource codeYou can also use the methods in the main method to view the usage of various functions of Unity:

 

Download Sample Code: Click here to download

(Note: The sample code in this article is based on vs2010 + unity2.0, so use vs2010 to open it. If vs2010 is not installed, copy the relevant code to the corresponding vs to run)

 

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)

Step 10. Use unity to decouple your system-Part2-learn how to use Unity (2)

Step 10: Use unity to decouple your system-Part2-learn how to use Unity (3)

Step 10: Use unity to decouple your system-Part3-dependency Injection

Step 10: Use unity to decouple your system-part4 -- unity & piab

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.