The AOP framework based on the Enterprise Library Piab has been widely used in company project development, but recently colleagues maintain an old project, using the Enterprise Library 2, so PIAB is in Enterprise Library 3.0 are introduced, so different direct use. To solve this problem, I wrote a simplified version of the AOP framework by using method hijacking (methods interception). (If the reader is not very knowledgeable about PIAB, you can refer to my article Ms Enterprise Library Policy injection Application Block for in-depth resolution [summary]).
First, how to use?
The programming method and Piab are basically the same, according to the specific requirements of the creation of the corresponding Callhandler, through the form of custom attribute Callhandler applied to the type or method above. Here is a simple example.
Namespace Artech.simpleaopframework
{
Class Program
{
static void Main (string[] args)
{
String UserID = Guid.NewGuid (). ToString ();
Instancebuilder.create<usermanager, Iusermanager> (). Createduplicateusers (UserID, Guid.NewGuid (). ToString ());
Console.WriteLine (' is ' user whose ID is \ ' {0}\ ' has been successfully created! {1} ", UserID, Userutility.userexists (UserID)?" Yes ":" No ");
}
}
public class Usermanager:iusermanager
{
[Transactionscopecallhandler (Ordinal = 1)]
[Exceptioncallhandler (Ordinal = 2, MessageTemplate = "Encounter Error:\nmessage:{message}")]
public void Createduplicateusers (string UserID, String userName)
{
Userutility.createuser (UserID, userName);
Userutility.createuser (UserID, userName);
}
}
public interface Iusermanager
{
void Createduplicateusers (String UserID, string userName);
}
}
In the example above, I created two Callhandler:transactionscopecallhandler and Exceptioncallhandler for transaction and exception handling. That is, we do not need to manually perform open, commit, and rollback operations of the transaction, nor do we need manual exception handling through the Try/catch block. To verify correctness, I simulate a scenario in which a user table (users) in the database is used to store user accounts, each with a unique ID, and now i insert two records with the same ID through the Usermanager createduplicateusers method. There is no doubt that if there is no transaction processing, the first user add will succeed and the second will fail. Conversely, if the transactionscopecallhandler that we add can work, two operations will be performed in the same transaction, and duplicate record additions will cause the transaction to be rolled back.
In Exceptioncallhandler, the thrown sqlexception is processed, where we simply print out the exception-related information. As for the information that you want to output, you can define an output template through the Exceptioncallhandlerattribute MessageTemplate property.
Run the program, we will get the result, fully proof of the existence of the transaction, the error message also according to the template we want to output.