[Entlib] Microsoft enterprise database 5.0 learning path-Step 10: Use unity to decouple your system-Part2-learn how to use Unity (3)

Source: Internet
Author: User
Tags first string

We will continue to introduce unity today.ArticleIn, I introduced the use of unitycontainer to register the relationship between objects, register the relationship between existing objects, and focuses on the use of various built-in Life Cycle managers in unity, today, we will mainly introduce some advanced applications of register and resolve in unity.

This article will mainly introduce:

1. register the type and initialize the constructor parameters and reload the call.

2. register the type and initialize the property parameters and reload the call.

3. Get objects with delay.

4. Search for registration information in the search container.

 

1. register the type and initialize the constructor parameters and reload the call.

When we use unity to register the relationship between objects, the object may have a corresponding constructor. The constructor needs to pass the corresponding parameters, and unity supports such registration, it mainly relies on the injectionconstructor class. First, let's look at the specific class constructor:

 
Public yourclass (string test, myclass my) {console. writeline (TEST); console. writeline (My. tostring ());}

This constructor has two parameters: a string and a myclass object. You can use the followingCodeTo register:

// Because the registered object has a constructor with parameters, you must provide the corresponding parameters when registering the type. // The injectionconstructor class is used here to implement the container. registertype <iclass, yourclass> (New injectionconstructor ("A", new myclass (); console. writeline ("----------- default call output -------------"); container. resolve <iclass> ();

In this way, you can complete object registration and inject the constructor parameters. Another requirement is that although the constructor parameters have been initialized during registration, but what should we do if we want to replace the previously registered value during the call?

In unity, this problem has been solved. We can implement it through parameteroverride and parameteroverrides. parameteroverride is for a parameter, while parameteroverrides is for the parameter list, the code for registering parameter initialization and parameter Overloading is as follows:

Public static void resolveparameter () {// because the registered object has a constructor with parameters, therefore, when registering a type, you need to provide the corresponding parameter // here the injectionconstructor class is used to implement the container. registertype <iclass, yourclass> (New injectionconstructor ("A", new myclass (); console. writeline ("----------- default call output -------------"); container. resolve <iclass> (); console. writeline ("----------- call output after reload -------------"); // The following two resolve methods have the same effect // 2nd methods can be used when there are too many parameters, if there is only one parameter, you can use 1st types // container. resolve <iclass> (New parameteroverride ("test", "test"), // new parameteroverride ("my", "New myclass "). ONTYPE <myclass> (); container. resolve <iclass> (New parameteroverrides () {"test", "test" },{ "my", new myclass ()}}. ONTYPE <yourclass> ());}

Note the following:

1. When you use the parameteroverride method to overload parameters, if the registered parameter is a specific object, you must use the ONTYPE Extension Method to specify the corresponding type. Otherwise, an error is returned.

2. When parameteroverrides is used to overload parameters, you can specify them using the code above, but you also need to use ONTYPE to specify them, however, the ONTYPE specifies the registered object type.

As follows:

It can be seen that the first string parameter has been changed after being reloaded.

 

2. register the type and initialize the property and reload the call.

This initialization property is similar to the above initialization parameter, except that the registration initialization of the property uses injectionproperty, while the overload property uses propertyoverride and propertyoverrides, the usage is the same. I will not introduce it here. The Code is as follows:

Public static void resolveproperty () {// initialize the object property container when registering the object relationship. registertype <iclass, myclass> (New injectionproperty ("name", "Class A"), new injectionproperty ("Description", "Class A description"); console. writeline ("----------- default call output -------------"); console. writeline (container. resolve <iclass> (). name); console. writeline (container. resolve <iclass> (). description); console. writeline ("----------- call output after reload -------------"); // The effect of the following two methods is the same, as shown in the preceding constructor parameter overload // var myclass = container. resolve <iclass> (New propertyoverride ("name", "Class A after heavy load"), // new propertyoverride ("Description ", "The description of the Class A after the overload"); var myclass = container. resolve <iclass> (New propertyoverrides () {"name", "overloaded Class A" },{ "Description ", "Description of Class A after heavy load "}}. ONTYPE <myclass> (); console. writeline (myclass. name); console. writeline (myclass. description );}

As follows:

We can see that both attributes have been reloaded.

Unity also provides us with a dependencyoverride overload. Its usage is similar to parameter overloading and attribute overloading. We will not demonstrate it here,However, it should be noted that dependencyoverride is an overload of the object type contained in the registered object type. For example, in class A, the constructor parameter is Class B, at the same time, there is also an attribute dependent on Class B. When dependencyoverride is used, all dependencies on Class B previously registered by this object A will change.. (For details, see resolvedependency in the sample code)

 

3. Delayed object acquisition

Another good feature of unity is its support for delayed acquisition. In essence, it is to establish a delegate in advance and then call the delegate. Let's look at the following code:

Public static void deferringresolve () {var resolver = container. Resolve <func <iclass> (); // perform other tasks based on the business logic. // Register the container between iclass and myclass. registertype <iclass, myclass> (); // obtain the myclass instance var myclass = resolver (); var resolver2 = container. resolve <func <ienumerable <iclass> (); // do other things according to the business logic. // Register an iclass-related object. Container. registertype <iclass, myclass> ("my"); container. registertype <iclass, yourclass> ("your"); // obtain all named instances associated with iclass var classlist = resolver2 ();}

This Code demonstrates two methods of obtaining latency, which are implemented by putting func <t> into resolve <t>. A delegate is returned, in this way, you can call this delegate as needed:

1. First, use resolve <func <iclass> (); to define the delegate for the object associated with iclass, and then register the relationship between iclass and myclass, then you can get it through resolver.

2. The second is to define the delegate for obtaining a list of named instances associated with iclass through resolve <func <ienumerable <iclass> (); in advance, then, call the corresponding delegate to obtain all the named instances associated with iclass at a time.

Both methods demonstrate that unity can more flexibly control object registration and object calling.

 

4. Retrieve registration information in the container

When we constantly use the unity container, we sometimes want to see how many objects are registered in the container and some information about each object, such: the information about what object is associated with what object, the specific registration name and the lifecycle manager used can be viewed in the registrations attribute of the container, you have a method in the Unity document to view the information. The Code is as follows:

Public static void displaycontainerregistrations (iunitycontainer thecontainer) {string regname, regtype, mapto, lifetime; console. writeline ("{0} registration information in the container:", thecontainer. registrations. count (); foreach (containerregistration item in thecontainer. registrations) {regtype = item. registeredtype. name; mapto = item. mappedtotype. name; regname = item. name ?? "[Default]"; lifetime = item. lifetimemanagertype. Name; If (mapto! = Regtype) {mapto = "->" + mapto;} else {mapto = string. empty;} lifetime = lifetime. substring (0, lifetime. length-"lifecycle manager ". length); console. writeline ("+ {0} {1} '{2}' {3}", regtype, mapto, regname, lifetime );}}

The specific registration code is as follows:

Public static void registerall () {container. registertype <iclass, myclass> ("my"); container. registertype <iclass, yourclass> ("your", new externallycontrolledlifetimemanager (); container. registertype <isubject, subject1> ("subject1"); container. registertype <isubject, subject2> ("subject2"); displaycontainerregistrations (container );}

As follows:

As you can see, all the information I registered in the code has been well reflected.

If you want to check whether an object has been registered, you can use container. isregistered <t> to verify it.

 

The above is all the content in this article. It mainly introduces some advanced applications of Unity's register and resolve. Good English friends can directly view the official documents 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.