Implementing Policy Injection in ASP.NET Applications

http://www.codeguru.com/csharp/.net/article.php/c17807

Introduction



Policy Injection Block was introduced in Enterprise Library 3.0 and makes use of aspect oriented programming concepts to add, remove, and modify common cross cutting concerns in your ASP.NET applications such as logging, validation, caching, exception handling, authorization, etc, without the need of recompiling the application's code. This article takes a quick tour of the policy injection block and aspect oriented programming concepts and discusses how the former can be implemented in ASP.NET applications to manage cross cutting concerns efficiently.


Pre-requisites


To use Policy Injection Block with ASP.NET 4.0, you should have the following installed in your system:


Microsoft Visual Studio 2010 RC or higher
Microsoft Enterprise Library 3.0 or higher
You can download a copy of Microsoft Enterprise Library from this link: http://entlib.codeplex.com/
Aspect Oriented Programming - What's that all about?


What is aspect oriented programming? AOP is a programming technique that you can use to implement cross cutting concerns in your application through the usage of policies to change the behavior of business objects and classes in your application. Such policies can be used to define and manage these cross cutting concerns declaratively. Note that aspect oriented programming is a new programming paradigm--not actually a replacement of object oriented programming. An aspect is simply a functionality, a feature or a cross cutting concern in an application. In essence, aspect oriented programming is a programming paradigm that compliments object oriented programming by allowing you to modify the static object model to design and implement a system that can be adaptable so as to accommodate future changes.


(Note: An aspect is the implementation of a crosscutting concern. AOP: aspect-oriented programming )


The Wikipedia states: "aspect-oriented programming (AOP) is a programming paradigm which isolates secondary or supporting functions from the main program's business logic. It aims to increase modularity by allowing the separation of cross-cutting concerns, forming a basis for aspect-oriented software development." Reference: http://en.wikipedia.org/wiki/Aspect-oriented_programming.


The policy injection application block from Microsoft is one such AOP framework. Some other popular AOP frameworks include: Spring.NET and Castle Dynamic Proxy.


What are Core and Cross Cutting Concerns?


Before we proceed with our discussion on the policy injection block, let's have a quick tour of a few basic concepts. What are concerns? A concern is basically a feature or a task implemented in an application. Tasks that are specific to the application are known as core concerns. You may think of tasks specific to an application like retrieving data from the database, performing some calculations or executing certain business rules as examples of core concerns of an application. On the contrary, the tasks that are common in the same application or across applications are commonly known as cross-cutting concerns. Typical examples of cross cutting concerns include: validation, logging, authorization, exception handling, transaction management and caching.


MSDN states: "concerns that implement the features of an object within the application, such as the business logic, are core concerns. Crosscutting concerns are the necessary tasks, features, or processes that are common across different objects--for example, logging, authorization, validation, and instrumentation. The purpose of the policy injection application block is to separate the core concerns and crosscutting concerns." Reference:


http://msdn.microsoft.com/en-us/library/ff650508.aspx
The Policy Injection Block - What is it and Why is it Needed?


The policy injection block from Microsoft is a flexible, extensible and easy to use framework that helps you to create policies to manage cross cutting concerns in your application effectively. In essence, the policy injection block facilitates simplifying and unifying the cross cutting concerns in your application and create policies to effectively manage them.


Why do we need the policy injection block anyway? Applications have a mix of core and cross cutting concerns. An application's business logic is an example of a core concern. Note that an application's business logic is contextual and hence cannot be reused most of the time. Cross cutting concerns in an application are reusable components that can be used across other layers of the same application or other applications. A clear isolation and good management of the core and cross cutting concerns of an application helps avoid duplicated and unmanageable code.


The policy injection block enables you to implement AOP functionality in your applications by intercepting method calls and then invoking handlers before and after those methods based on pre-defined configuration information. You can use the policy injection block to:


Create handlers for each of the cross cutting concerns that your application will use
Define the conditions where each cross cutting concern would apply
Define and manage behaviour of each of the cross cutting concerns through configuration
The policy injection block includes a collection of the following:


Handlers
Attributes
Matching Rules

The Matching Rules are used to indicate the methods that need to be intercepted and the handlers are used to specify what should happen before or after a method interception occurs.


The policy injection block includes the following set of built-in matching rules that can be used to select the classes to which a handler pipeline would be associated:


AssemblyMatchingRule
CustomAttributeMatchingRule
MemberNameMatchingRule
MethodSignatureMatchingRule
NamespaceMatchingRule
ParameterTypeMatchingRule
PropertyMatchingRule
ReturnTypeMatchingRule
TagAttributeMatchingRule
TypeMatchingRule
Each policy can have one or more handlers. You have the following set of built-in handlers that you can use to the handler pipeline:


Authorization Handler
Caching Handler
Exception Handling Handler
Logging Handler
Performance Counters Handler
Validation Handler
The Policy configuration information can be stored in your application's configuration in the format shown in the code snippet below:


  <policyInjection>
      <policies>
          <add name="Policy1">
            <matchingRules>
              <add name="MatchingRuleA" ... />
              <add name="MatchingRuleB" ... />
            </matchingRules>
            <handlers>
              <add name="HandlerA" ... />
              <add name="HandlerB" ... />
            </handlers>
          </add>
          <add name="Policy2">
            <matchingRules>
              <add name="MatchingRuleC" ... />
              <add name="MatchingRuleD" ... />
            </matchingRules>
            <handlers>
              <add name="HandlerC" ... />
              <add name="HandlerD" ... />
            </handlers>
          </add>
      </policies>
  </policyInjection>
Using the Policy Injection Block


To use the policy injection block in your applications, follow these steps:


Open the Microsoft Visual Studio 2010 IDE
Create an ASP.NET Application with some basic code
Identify the objects in the application that need to be intercepted
Add the necessary references to the policy injection block and its dependent assemblies
Add the policy injection block settings in the app.config file
Create a policy to be used to use the policy injection block to apply the cross cutting concerns in the application
Create matching rules within the policies you defined
Now specify the handlers to be executed for the rules that match
The configuration details would be structured as shown in the code snippet below:


<policies>
   <add name="Logging">
       <matchingRules>
           //Add the rules here
       </matchingRules>
       <handlers>
           <add
           //Add the handlers here
           </add>
       </handlers>
   </add>
</policies>
Add the handlers to the handler pipeline
Lastly invoke Policy Injection in your code to manage the cross cutting concerns
Consider the following interface ICustomer that declares a method GetCustomerName.


  public interface ICustomer
  {
      String GetCustomerName(string customerCode);
  }
Now suppose when the GetCustomerName(String) method is called, we would intercept the call and log the information. To do this, we need to use TagMatching rule. This implies that we would need to add a tag to the GetCustomerName(String) method. The updates ICustomer interface would now look like as shown below:


  public interface ICustomer
  {
      [Tag("LogMethod")]
      String GetCustomerName(String customerCode);
  }
  
  public class Customer : ICustomer
  {
      public String GetCustomerName(string customerCode)
      {
         //Code to return customer name based on customer code
      }
  }
The next step is to define a policy in the application's configuration file so that the call to the method having the [Tag("LogMethod")] is intercepted and the information logged using the Logging Application Block. Here's how the policy injection configuration would now look like:


  <policyInjection>
      <policies>
          <add name="Logging">
              <matchingRules>
                  <add type="Microsoft.Practices.
      EnterpriseLibrary.PolicyInjection.MatchingRules.
      TagAttributeMatchingRule, 
       Microsoft.Practices.EnterpriseLibrary.PolicyInjection,
       Version=2.9.9.2, Culture=neutral,
       PublicKeyToken=b03f5f7f11d50a3a"
                        name="Tag Matching Rule"
               match="LogMethod" ignoreCase="true" />
              </matchingRules>
              <handlers>
                  <add name="Logging Handler"
        type="Microsoft.Practices.EnterpriseLibrary.
       PolicyInjection.CallHandlers.LogCallHandler,
                          Microsoft.Practices.
        EnterpriseLibrary.PolicyInjection.CallHandlers,
        Version=2.9.9.2, Culture=neutral,
       PublicKeyToken=b03f5f7f11d50a3a"
                          logBehavior="Before"
       beforeMessage="Before" includeParameterValues="true"
       includeCallTime="true" includeCallStack="false"
       severity="Information">
                      <categories>
                          <add name="General" />
                      </categories>
                  </add>
              </handlers>
          </add>
      </policies>
  </policyInjection>
The following code snippet illustrates how the policy injection block can be used to instantiate the customer class and invoke its method:


  ICustomer customer =
      PolicyInjection.Create<Customer, ICustomer>();
  customer.GetCustomerName("C001");
The call to this method would then be logged appropriately as defined in the logging provider of the logging application block.


Summary


The policy injection block allows you to declaratively define and manage the cross cutting concerns in your application. It allows you to specify the cross cutting concerns in an application in terms of policies. You can use the policy injection block to log method invocations, cache results from a method, analyze the performance of a method, handle and log exceptions, validate method parameters, etc. This article provided the readers a head start to the concepts of Aspect Oriented Programming and policy injection block and strategies to implement them in your ASP.NET applications. Happy reading!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值