Application of Attribute in. NET Programming (4)

Source: Internet
Author: User

Application of Attribute in Interception Mechanism

From this section, we will discuss the advanced application of Attribute. For this reason, I have prepared a practical example: we have an order processing system. When an order is submitted, the system checks the inventory, if the inventory quantity meets the order quantity, the system records the order processing record, and then updates the inventory. If the inventory quantity is lower than the order quantity, the system makes a corresponding record and sends an email to the inventory administrator. For ease of demonstration, we have simplified the example:

// Inventory. csusing System; using System. collections; namespace NiwalkerDemo {public class Inventory {private Hashtable inventory = new Hashtable (); public Inventory () {inventory ["Item1"] = 100; inventory ["Item2"] = 200;} public bool Checkout (string product, int quantity) {int qty = GetQuantity (product); return qty> = quantity ;} public int GetQuantity (string product) {int qty = 0; if (inventory [product]! = Null) qty = (int) inventory [product]; return qty;} public void Update (string product, int quantity) {int qty = GetQuantity (product ); inventory [product] = qty-quantity ;}}// Logbook. csusing System; namespace NiwalkerDemo {public class Logbook {public static void Log (string logData) {Console. writeLine ("log: {0}", logData) ;}}// Order. csusing System; namespace NiwalkerDemo {public class Order {private int orderId; private string product; private int quantity; public Order (int orderId) {this. orderId = orderId;} public void Submit () {Inventory inventory = new Inventory (); // create an inventory object // check the Inventory if (inventory. checkout (product, quantity) {Logbook. log ("Order" + orderId + "available"); inventory. update (product, quantity);} else {Logbook. log ("Order" + orderId + "unavailable"); SendEmail () ;}} public string ProductName {get {return product ;}set {product = value ;}} public int OrderId {get {return orderId;} public int Quantity {get {return quantity;} set {quantity = value ;}} public void SendEmail () {Console. writeLine ("Send email to manager ");}}}


The following is the calling program:
 

//AppMain.csusing System;namespace NiwalkerDemo{   public class AppMain   {      static void Main()      {         Order order1=new Order(100);         order1.ProductName="Item1";         order1.Quantity=150;         order1.Submit();                  Order order2=new Order(101);         order2.ProductName="Item2";         order2.Quantity=150;         order2.Submit();      }   }}

The program looks good. Business Objects encapsulate business rules and the running results also meet the requirements. But I seem to have heard you complain, aren't you? When your customer's needs change (customers always change their needs), for example, the inventory check rules are not a single inspection product quantity, we also need to check whether the product has been reserved in many situations, so you need to change the Inventory code and modify the code in Order. Our example is just a simple business logic, the actual situation is much more complicated than this. The problem is that the Order object is tightly coupled with other objects. From the perspective of OOP, this design is problematic. If you write such a program, at least it will not be passed in my team.

You said, "No problem! We can extract the business logic into a specially designed object for processing transactions ." Well, good idea. If you think so, maybe I can give you a proposal to use Observer Design Pattern (Observer Design Pattern): You can use delegate, define a BeforeSubmit and AfterSubmit event in the Order object, create an object linked list, and insert the related objects into the linked list. In this way, you can intercept Order submission events, automatically perform necessary transaction processing before and after Order submission. If you are interested, you can write such a code by yourself, or consider how to handle the interaction between objects in a distributed environment (Order and Inventory are not in the same place.

Fortunately,. NET Framework provides support for implementing this technology. In. object Remoting in the net Framework and Component Service have an important interception mechanism. In object Remoting, object interaction between different applications needs to cross their domain boundaries, each application domain can be subdivided into multiple contexts, and each application domain has at least one default Context. Even in the same application domain, there is a problem of traversing different contexts. . NET Component Service has developed the COM + component service, which uses Context Attribute to implement the same Interception Function as COM +. By intercepting call objects, we can pre-process and post-process a method call, and solve the above cross-border problem.

You need to be reminded that if you check ContextAttribute IN the MSDN document, I can ensure that you do not get any information that helps you understand ContextAttribute. What you see will be the following sentence: "This type supports. NET Framework infrastructure and is not intended to be used directly from your code. "--" This type is supported. NET Framework, which is not intended to be directly used for your code." However, on the msdn site, you can see some relevant information (see the reference link after the article ).

The following describes several classes and concepts. The first is:

ContextAttribute class

ContextAttributeDerived from Attribute. It also implements the IContextAttribute and IContextProperty interfaces. All custom contextattributes must be derived from this class.
Constructor:
ContextAttribute:The ContextAttribute is configured with a parameter.

Public attributes:
Name: Read-only attribute. Returns the name of ContextAttribute.

Public method:
GetPropertiesForNewContext: Virtual method. Add a property set to the new Context.
IsContextOK:Virtual method. Query whether the specified attribute exists in the customer Context.
IsNewContextOK:Virtual method. Returns true by default. An object may have multiple contexts. Use this method to check whether the attributes in the new Context conflict.
Freeze:Virtual method. This method is used to locate the last position of the created Context.

ContextBoundObject class

The ContextBoundObject class derives from the ContextBoundObject class. The object of this class uses Attribute to specify the Context where it is located. All calls that enter this Context can be intercepted. This class is derived from MarshalByRefObject.

The following interfaces are involved:

IMessage:Defines the implementation of the sent message. A message must implement this interface.

IMessageSink: Defines the interface of the Message Receiver. A Message Receiver must implement this interface. There are also several interfaces. We will introduce them in the next section based on the Implementation Principles of the Interception Architecture.
(To be continued)

 

 

(Bearing the previous section ). in the design of the NET Framework interception mechanism, there are a variety of message receivers between the client and the object. These message receivers form a linked list, and the client's call object process and call return implement interception, you can customize your own message receivers and insert them into the linked list to complete the pre-processing and post-processing of a call. So how is call interception structured or implemented?

In. NET has two types of calls, one is cross-application Domain, the other is cross-Context, and the two types of calls both use the intermediate proxy ), proxy is divided into two parts: transparent proxy and actual proxy. The transparent proxy exposes the same public entry point as the object. When the client calls the transparent proxy, the transparent proxy converts the frames in the stack to messages (the object that implements the IMessage interface mentioned in the previous section ), the message contains the method name, parameters, and other attribute sets, and then passes the message to the actual proxy.

Related Article

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.