2011-04-12 80 views
1

我试着写,将执行定义的静态方法,试图减少对锅炉的代码和增加可读性的实用程序类。执行泛型委托原型

我的想法从我目前的WCF服务,所有方法都排除了服务请求的统一锅炉代码模式改写我们的aspx web服务的项目茎。静态方法目前不存在于我们现有的对象中,因为大多数逻辑都在Web服务方法本身内部,但应该易于转移。

什么我到目前为止下面是一个例子。

[DataContract] 
public CustomObject CreateItem(int id, string name) 
{ 
    return ExecuteMethod<CustomObject>(CustomObject.CreateItem, id, name); 
} 

protected static T ExecuteMethod<T>(Delegate methodToExecute, params object[] parameters) 
{ 
    // Do some basic logging 
    // Authenticate user 

    try 
    { 
     if (methodToExecute == null) 
     { 
      throw new Exception(); 
     } 

     if (methodToExecute.Method.ReturnType != typeof(T)) 
     { 
      throw new Exception(); 
     } 

     if (methodToExecute.Method.GetParameters().Length != parameters.Length) 
     { 
      throw new Exception(); 
     } 

     return (T)methodToExecute.Method.Invoke(methodToExecute, parameters); 
    } 
    catch 
    { 
     throw new SoapException("There was an error", SoapException.ClientFaultCode); 
    } 
} 

public class CustomObject 
{ 
    [DataMemeber] 
    public int Id { get; set; } 
    [DataMember] 
    pubic string Name { get; set; } 

    internal static Delegate CreateItem = new Func<int, string, CustomObject>(
     (id, name) => 
     { 
      return new CustomObject() { Id = 1, Name = name }; 
     } 
    ); 
} 

我上面的示例应该说明我正在努力实现的目标。但是,我觉得这种方法到目前为止失败的原因是传递给泛型方法的参数没有输入,并可能导致运行时错误(对于返回类型和参数类型)

我已经添加了一些基本检查,如检查的MethodInfo的返回类型为同一类型为T和方法的参数个数等于传入参数的数量,但并不感到“安全”的。

上午我在正确的轨道,或者我应该考虑的替代方案?

这只是目前的原型,因为我刚开始考虑重新设计。

+1

什么时候MyHelpers.ExecMethod(MyMethod,params)'比'MyMethod(params)'更容易? – 2011-04-12 15:35:47

回答

2

它看起来好像只有通过您的方法调用它的好处是将任何异常转换为SoapException。你可以这样做更容易这样的:

protected static T ExecuteMethod<T>(Func<T> function) 
{ 
    try 
    { 
     return function(); 
    } 
    catch 
    { 
     throw new SoapException("There was an error", 
           SoapException.ClientFaultCode); 
    } 
} 

然后调用代码是这样的:

public CustomObject CreateItem(int id, string name) 
{ 
    return ExecuteMethod(() => CustomObject.CreateItem(id, name)); 
} 

(我希望你有一些日志记录的异常情况真正的代码,顺便说一句)

+0

哦 - 太好了。我一直在努力弄清楚它的工作原理,但你的例子很好地证明了这一点,并且这种模式似乎很适合实现我整理服务方法的目标。 是的,我将实施更强大的异常情况处理解决方案 - 这只是为了测试,但可能对她太多了。 感谢Jon – Mike 2011-04-12 15:47:52