Enterprise Library-Unity Application Block learning Manual (Latest Version) Part 1

Source: Internet
Author: User
This article demonstrates how to use the Enterprise Library-Unity Application Block dependency injection module. Unity is a lightweight, scalable dependency injection container designed and developed by the Microsoft pattern & Practices Team. It provides constructor, attribute, and method call injection. (1) simplified object establishment, especially for hierarchical object structures and dependencies, and simplified code. (2) supports abstract requirements. allows developers to specify dependencies at runtime or in configuration files, which simplifies the management of issues of interest in software development. (3) By using containers to delay component configuration, the flexibility is improved. (4) The service positioning function allows the client to store or cache containers. This feature is particularly useful in ASP. NET websites. developers can store the entire container in session or application. This article describes how to use unity iner to create and connect application objects. Replace the constructor of the call class and common methods for setting attribute values with the correct unity iner. This article by the http://blog.entlib.com open source ASP. Net blog platform team according to the entlib Hol manual compilation to provide, welcome to exchange. Exercise 1: Use unity containerFirst, open the stockticker. sln solution project file under the labs \ lab01 \ begin \ stocksticker directory. Run the sample program. On the application interface, enter the stock code, such as GM. Then, click the subscribe button and select the refresh check box. The latest information about the subscribed stock code is displayed in the window, and refresh the page every time you receive the stock information. As shown in:
The default configuration of the application is to obtain stock information from moneycentralremote, which provides online and real-time stock market data. The console interface displays the log for updating stock information. The UI. Log File (under the stocksticker \ bin \ DEBUG directory) contains operation information on the user interface. 1. The sample program is created based on the Model-View-Presenter (MVP) mode. For MVP update information, refer to the msdn article. Shows the classes involved in the sample program and their relationships.
 
Stockstickerform implements the user interface. istockquoteservice defines a service interface for retrieving the current stock price. moneycentralstockservice is the specific implementation of this interface. The ilogger interface and its specific implementation are used to record operation logs. Finally, stockstickerpresenter completes the displayed role. Before starting the user interface, the static method program. Main () creates all objects involved in sequence and connects them to each other. The goal of this article is to use unity iner instead of explicitly creating these objects. 2. Add references to necessary assembly to the stockticker project, and add references to Microsoft. Practices. Unity and Microsoft. Practices. objectbuilder2 assembly.
3. Update the startup code, use unity iner to open the program. CS file, and add references to the unity namespace. Using Microsoft. Practices. Unity; Use the Resolve Method of the unitycontainer object to create a stockstickerpresenter object instance instead of the Code for creating view, presenter, service, and logger object instances. The Code is as follows. Static void main () {application. enablevisualstyles (); application. setcompatibletextrenderingdefault (false); // todo use a container to create the objects here using (iunitycontainer Container = new unitycontainer () {stockstickerpresenter presenter = container. resolve <stockstickerpresenter> (); application. run (form) presenter. view);} application. run (form) presenter. view);} unity container implements Idi Sposable interface, so the above Code uses the using statement to release the container object. If you are currently running the sample program, a resolutionfailedexception exception will be thrown, which indicates that the attempt to parse stockstickerpresenter fails. The following code uses the registertype method to increase the type ing required by the iner parsing interface. Using (iunitycontainer Container = new unitycontainer () {container. registertype <istockstickerview, stockstickerform> (). registertype <istockquoteservice, moneycentralstockquoteservice> (); stockstickerpresenter presenter = container. resolve <stockstickerpresenter> (); application. run (form) presenter. view);} The registertype method is used to set the main mechanism of container. It can be used to map abstract types to specific classes, it can also be used to reload default injection rules and specify the life cycle manager). The above Code does not contain the ilogger interface ing, which is not mandatory at present, because the property has not been injected, unless explicitly configured. Now, the sample program can run normally, because all the objects involved can be parsed by the container, but no logs are logged, because logger is not injected into the object to be parsed. Now, run the sample program. The sample program can work normally, except that the log information is not displayed in the console window and UI. log file. 4. Attributes injection can be used to overload default injection rules. In some cases, attributes can be used to select the member injection that will be ignored according to the default rules. When attributes is used for property injection, we usually want to use container to set the property. In addition, the dependency is imported through the constructor. Set the injection for the logger attribute of the moneycentralstockquoteservice class (1) Open stockquoteservices \ moneycentralstockquoteservice. CS file (2) add reference to unity namespace using Microsoft. practices. unity; (3) Add the dependency attribute for the logger attribute. The Code is as follows. Private ilogger logger; [dependency] public ilogger logger {get {return logger;} set {logger = value ;}} dependency attribute indicates that this attribute type should be injected, the parsing Type in the container is ilogger. (4) Add the ilogger type registration to enable ilogger interface parsing to open the program. CS file, and use the registertype method of the iner class to implement the ing between the ilogger interface and the consolelogger class. The Code is as follows. Using (iunitycontainer Container = new unitycontainer () {container. registertype <istockstickerview, stockstickerform> (). registertype <istockquoteservice, moneycentralstockquoteservice> (). registertype <ilogger, consolelogger> (); stockstickerpresenter presenter = container. resolve <stockstickerpresenter> (); application. run (form) presenter. view);} 5. running the sample program now runs the sample program. The operation logs of service calls are recorded in the console window, but the operations on the user interface are Not recorded in the console window, because the logger attribute of the presenter class is still not injected. Set the logger attribute of the injection stockstickerpresenter class to be the same as the previous operation. The dependency attribute is also applied to the presenter class. Then, because a different logger instance is injected, the Unity container supports multiple registrations of the same type, but each time there is a different name. When parsing dependencies, different instances are returned Based on the specified names. (1) Open the UI \ stockstickerpresenter. CS file and add references to the unity namespace. (2) Add the dependency attribute to the logger attribute and name it UI. The Code is as follows. (3) Use the UI name to add type registration and parse the ilogger interface. Open the program. CS file, use the registertype method to map the ilogger interface to the tracesourcelogger class, and input the UI name. The Code is as follows. Using (iunitycontainer Container = new unitycontainer () {container. registertype <istockstickerview, stockstickerform> (). registertype <istockquoteservice, moneycentralstockquoteservice> (). registertype <ilogger, consolelogger> (). registertype <ilogger, tracesourcelogger> ("UI"); stockstickerpresenter presenter = container. resolve <stockstickerpresenter> (); application. run (form) presenter. view);} if the current When running the sample program and parsing the logger attribute of the presenter as the tracesourcelogger instance, an exception is thrown. Along the innerexpceptions chain, find the final exception information as invalidoperationexpceiton-the type tracesourcelogger has multiple constructors of length 1. Unable to disambiguate. This is because the default unity injection rules cannot identify how to build object instances, so the container must be explicitly configured. (4) use injectionconstructor attribute to explicitly specify the constructors used to create the tracesourcelogger object instance to open the loggers \ tracesourcelogger. CS file and add references to the unity namespace. Using Microsoft. Practices. Unity; Add the injectionconstructor attribute to the constructor in one of tracesourcelogger. The constructor receives the unique tracesource parameter. The Code is as follows. [Injectionconstructor] public tracesourcelogger (tracesource) {This. tracesource = tracesource;} 5. add instance registration to parse the specified constructor of the tracesource type in the previous step. The default injection rule of unity will use this constructor and parse it. net Framework tracesource object instance, and pass in the constructor as a parameter. Because tracesource is a built-in class of. NET Framework, you cannot add attrubite. Therefore, you will create an object instance using the code and provide it to the container. (1) Open the program. CS file and use the registerinstance method to indicate that the returned object instance will be parsed when the tracesource class is parsed. The sample code is as follows. Using (iunitycontainer Container = new unitycontainer () {container. registertype <istockstickerview, stockstickerform> (). registertype <istockquoteservice, moneycentralstockquoteservice> (). registertype <ilogger, consolelogger> (). registertype <ilogger, tracesourcelogger> ("UI "). registerinstance (New tracesource ("UI", sourcelevels. all); stockstickerpresenter presenter = container. resolve <stocksticke Rpresenter> (); application. run (form) presenter. view);} Now the sample program is running and can work properly. The UI operation log is recorded in the UI. in the log file, messages from the service are displayed in the console window. Attributes is a convenient mechanism to overload or eliminate the default injection rules of the ambiguous iner, but it may cause fragile dependencies, especially dependency names, because hard encoding is required in the source code. The next section demonstrates other optional mechanisms to externalize the container settings without involving the objects to be created. Http://www.entlib.com professional ASP. NET e-commerce platform team, welcome to continue to visit the unity Application Block learning manual. Reference:Unity Application Block hands-on labs for Enterprise Library

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.