Thursday, August 12, 2004 11:37 AM
tbrem
Take ICommand with Attributes
The latest issue of MSDN Magazine (http://msdn.microsoft.com/msdnmag/issues/04/09/default.aspx) has an interesting article on applying the Command Pattern to the problem of distributed systems. It proposes a neat technique of essentially encapsulating some piece of work within a Command and shipping that off via MSMQ to have some other endpoint process it.
This is cool stuff as I like the use of ICommand's to encapsulate data processing associated with a physical store abstracted away from the data entities. For example, a Model object (binds data and the rules internal towith it) can use ICommand's as a persistence layer to work with any underlying store, freeing it from direct dependancies on a Database, a Web Service, a Queue, etc.
One issue with the proposed delegation of Execute() over the proverbial wall is the loss of security and other aspects that should be applied to the execution. One way to resolve this is to combine the Command pattern with the Template method pattern to implement an interception framework embedded into the Command to ensure proper safety with Execute().
For example:
Public Interface ICommandAttribute Sub PreExecute(ByVal cmd As ICommand) Sub PostExecute(ByVal cmd As ICommand) End Interface
Public MustInherit Class Command : Implements ICommand Public Sub Execute() Implements ICommand.Execute Dim ICommandAttrs As ICommandAttributes() = _ Me.GetType().GetCustomAttributes(GetType(ICommandAttribute), True)
For Each ICommandAttr in ICommandAttrs
ICommandAttr.PreExecute()
Next
Me.MyExecute()
For Each ICommandAttr in ICommandAttrs
ICommandAttr.PostExecute()
Next
End Sub Protected MustOverride Sub MyExecute() End Class So creating a custom attribute that implements ICommandAttribute allows you encapsulate any sort of aspect that may need to be enforced with the Command. An AuthorizationAttribute could check the current thread's IPrinicpal and check that it is valid for Execution of this Command, preventing rogue processes from picking Commands off the queue and firing them adding security to the distributed Command. Later, I'll blog a bit more about the Model / ICommand relationship...