gpt4 book ai didi

wcf - 您如何实现应该为所有方法调用的基本方法?

转载 作者:行者123 更新时间:2023-12-04 18:18:39 25 4
gpt4 key购买 nike

我有产品服务。在每次调用服务时,我都想调用一个方法。在这种情况下,我正在记录。我正在寻找一种方法,而不是在每个方法中都写 using 语句。但我仍然希望在每次通话时都进行日志记录。我该怎么做呢?

    public class ProductService : IProductService
{
public IList<Product> GetProductsByBrand(int BrandID)
{
using (new Logging())
{
// Get a list of products By Brand
}
return new List<Product>();
}

public IList<Product> Search(string ProductName)
{
using (new Logging())
{
// Search
}
return new List<Product>();
}

public static string OrderProducts(IList<Order> Orders, Payment paymentDetials)
{
string AuthCode;
using (new Logging())
{
// Order and get the AuthCode
}
AuthCode = "";
return AuthCode;
}
}

最佳答案

你听说过 AOP(面向切面编程)吗?这是一种将横切关注点实现为可重用方面的方法,这些方面围绕目标类型进行包装,并在它们包装的方法之前或之后执行额外的处理。

http://en.wikipedia.org/wiki/Decorator_pattern

在 WCF 环境中,这通常通过将“行为”应用于您的服务类来完成。在这种情况下,我建议使用实现 IParameterInspector 的属性的 IOperationBehavior 接口(interface),以便在传递参数之前查看参数,然后创建和调用服务实例。这是一篇有用文章的链接,该文章更深入地介绍了扩展 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,
};
}

关于wcf - 您如何实现应该为所有方法调用的基本方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11172897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com