보일러 코드를 줄이고 가독성을 높이기 위해 정의 된 정적 메서드를 실행할 유틸리티 클래스를 작성하려고합니다.일반 대리자 프로토 타입 실행
내 생각은 우리의 aspx 웹 서비스를 모든 메소드가 서비스 요청을 제외하고 균일 한 보일러 코드 패턴을 갖는 WCF 서비스로 다시 작성하는 현재 프로젝트에서 기인합니다. 정적 메서드는 현재 대부분의 논리가 웹 서비스 메서드 자체 내에 있지만 쉽게 전송할 수 있어야하므로 기존 개체에 존재하지 않습니다.
지금까지 내가 가진 것의 예가 아래에 있습니다.
[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와 동일한 유형이며 메서드의 매개 변수 수가 전달 된 매개 변수의 수와 같지만 '안전함'을 느끼지 못합니다.
올바른 방향으로 가고 있습니까 아니면 대안 솔루션을 조사해야합니까?
이것은 재 설계에 대해 생각하기 시작한 순간의 프로토 타입 일뿐입니다.
언제 MyHelpers.ExecMethod (MyMethod, params)가'MyMethod (params)'보다 더 쉬울 수 있습니까? –