你听说过 AOP(面向方面编程)吗?这是一种将横切关注点实现为可重用方面的方法,这些方面围绕目标类型进行包装,并在它们包装的方法之前或之后执行额外的处理。
http://en.wikipedia.org/wiki/Decorator_pattern
在 WCF 环境中,这通常通过将“行为”应用于您的服务类来完成。在这种情况下,我建议使用实现 IParameterInspector 的属性的 IOperationBehavior 接口,以便在创建和调用服务实例之前查看参数。这是一篇有用文章的链接,该文章更深入地介绍了扩展 wcf 消息管道的选项。
http://msdn.microsoft.com/en-us/magazine/cc163302.aspx
//Attribute class
public class LogOperationBehavior : Attribute, IOperationBehavior, IParameterInspector {
public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) {
return;
}
public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation) {
//clientOperation.ParameterInspectors.Add(new ClientParameterInspector());
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation) {
dispatchOperation.ParameterInspectors.Add(this);
}
public void Validate(OperationDescription operationDescription) {
return;
}
#region IParameterInspector Members
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) {
//perform logging after
}
public object BeforeCall(string operationName, object[] inputs) {
//perform logging before
return null;
}
#endregion
}
public class BusinessOperation : IBusinessOperation {
//Apply to your service via an attribute
[LogOperationBehavior]
public DivideResponse DivideTwoNumbers(DivideRequest dr) {
return new DivideResponse() {
Answer = dr.Numerator/ dr.Demoninator2,
};
}