2012-06-29 4 views
1

아래 샘플에서 호출 전후에 반복되는 한 쌍의 줄을 피하는 방법은 무엇입니까? 세부 정보 : 이것은 실제 크기가 더 큰 코드의 컴파일 가능한 모의입니다. 일반적으로 다양한 API를 가진 서비스 클라이언트를 포함하는 프록시 클래스 계층입니다. 반복되는 부분은 모든 클라이언트의 모든 메소드에 대한 사전 호출 및 사후 호출입니다. 불행히도 가능한 모든 메소드에 대해 단일 서명이 없기 때문에 사전 및 사후 파트에는 클라이언트의 채널 및 컨텍스트에 대한 포인터가 필요합니다. AOP, Generics, Delegates, Attributes 등과 같은 고급 기능을 적용 할 수 있습니까? 주셔서 감사합니다서로 다른 서명을 가진 전후 호출 방법

using System; 

namespace ConsoleApplication 
{ 
class ClassServiceClient: IDisposable 
{ 
    public Object channel() 
    { 
     return "something"; 
    } 

    public Object context() 
    { 
     return "something other"; 
    } 
} 

class ClassA : ClassServiceClient 
{ 
    public Object methodA() 
    { 
     return "something other"; 
    } 
} 

class ClassB : ClassServiceClient 
{ 
    public void methodB(string param) 
    { 
     return; 
    } 
} 

class ClassAProxy 
{ 
    public Object methodA() 
    { 
     using (ClassA client = new ClassA())   
     { 
      Program.preparation(client.channel()); //<---- repetitive part 
      Object result = client.methodA(); 
      Program.postinvocation(client.context());//<---- repetitive part 
      return result; 
     } 
    } 
} 

class ClassBProxy 
{ 
    public void methodB(string param) 
    { 
     using (ClassB client = new ClassB()) 
     { 
      Program.preparation(client.channel()); //<---- repetitive part 
      client.methodB(param); 
      Program.postinvocation(client.context());//<---- repetitive part 
      return; 
     } 
    } 
} 


class Program 
{ 
    public static void preparation(Object channel) 
    { 
     // Do something with channel 
    } 

    public static void postinvocation(Object context) 
    { 
     // Do something with context 
    } 

    static void Main(string[] args) 
    { 

    } 
} 
} 
+1

은 PostSharp 같은 Aspect 지향적 인 프로그래밍 프레임 워크를 살펴 보자를 // www가 .sharpcrafters.com / –

답변

1

당신이 공통 기본 클래스를 사용할 수 있다면, 당신은 쉽게 호출과 논리를 수행하는 보호 추상적 인 방법, 예를 수행하는 공공 밀봉 방법을 사용할 수 있습니다

class ProxyBase{ 
    public void Method(params object[] args){ 
     PreConditions(); 
     Invoke(args);    
     PostConditions(); 
    } 

    protected abstract void Invoke(object[] args); 
} 

class ClassAProxy{ 
    protected override void Invoke(object[] args){ 
     client.Method(args[0]); 
    } 
} 

당신은 행동한다 프로그램 클래스에서의 InvocationHandler 선언하여 비슷한 결과를 기능적으로 얻을 수 있습니다 : HTTP :

class Program{ 
    public static void Invoke(object[] args, Action action){ 
     PreConditions(); 
     action(); 
     PostConditions(); 
    } 
} 

class ClassAProxy{ 
    public void MethodA(int i){ 
     Program.Invoke(() => client.Something(i)); 
    } 
} 
관련 문제