【发布时间】:2014-01-14 12:11:20
【问题描述】:
我们有一个 wcf Web 服务 API,它有一些通用代码,我们将这些代码封装到一个通用方法中,以免在每个 Web 服务方法中编写相同的代码。看起来像这样:
TResult SafeMethodCall<T, TResult>(Func<T, TResult, TResult> body, T request)
where TResult : ServiceResponse, new()
where T : RequestBase
{
if (request == null)
throw new ArgumentNullException("request");
var response = new TResult();
try
{
response = body(request, response);
}
catch (Exception ex)
{
AddServiceError(response, ex);
}
finally
{
AddAuditData(request, response);
}
return response;
}
现在我正在尝试编写审计功能,并且有一个特定参数几乎总是请求或响应类的一部分,因此我可以使用反射获取此参数,以便将其记录到数据库中。
private void AddAuditData(RequestBase request, ServiceResponse response)
{
string signinId = "";
Type t = request.GetType();
PropertyInfo info = t.GetProperty("SignInIdentifier");
if (info != null)
{
signinId = info.GetValue(request).ToString();
}
Type r = response.GetType();
info = r.GetProperty("SignInIdentifier");
if (info != null)
{
signinId = info.GetValue(response).ToString();
}
//now log signinid, and method name, etc to the database
//how do I pass signinid into this method if it isn't part of the request or response???
}
每个 Web 服务方法都有自己版本的响应和请求类,它们继承自该方法中引用的基本类。
我的问题是,对于我无法访问要记录的参数的一两个 Web 服务方法,但我需要做一些工作来获取它,我不确定如何传递它进入泛型方法来处理它。
我可以通过使用全局变量或将其添加到响应类中来做到这一点,但是从编程风格的角度来看,这两种方法中的任何一种都显得相当劣质。
我想知道是否有人对处理此问题的“好”方式有任何其他建议?
【问题讨论】: