Search code examples
c#aspect

Aspect orientation in C#


I have a FTPDataTransfer-class that has a state (FTPDataTransferState). This class provides a lot of transfer-methods like ReceiveData (overloaded), SendData, ... How can I change the state to Ready, Transfer, ... without chaning the value in every transfer-method?


Solution

  • You can use PostSharp for this. In more detail, the OnMethodBoundaryAspect is the aspect you want to use. In your case it could look like:

    using PostSharp.Aspects;
    
    [Serializable]
    public sealed class ReadyOnExit : OnMethodBoundaryAspect
    {
        public override void OnExit(MethodExecutionArgs args)
        {
            var state = (FTPDataTransferState)args.Instance;
            state.Transfer(FTPDataTransferState.Ready);
        }
    }