2013-01-21 48 views
3

我可能錯過了一些非常簡單的事情。Castle DynamicProxy - 'classToProxy'必須是類

我只是想寫一個非常簡單的動態代理使用示例 - 我基本上想攔截調用並顯示方法名稱和參數值。我的代碼如下:

public class FirstKindInterceptor : IInterceptor 
{ 
    public void Intercept(IInvocation invocation) 
    { 
     Console.WriteLine("First kind interceptor before {0} call with parameter {1} ", invocation.Method.Name, invocation.Arguments[0]); 
     invocation.Proceed(); 
     Console.WriteLine("First kind interceptor after the call"); 
    } 
} 

public interface IFancyService 
{ 
    string GetResponse(string request); 
} 

public class FancyService : IFancyService 
{ 
    public string GetResponse(string request) 
    { 
     return "Did you just say '" + request + "'?"; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var service = new FancyService(); 
     var interceptor = new FirstKindInterceptor(); 
     var generator = new ProxyGenerator(); 
     var proxy = generator.CreateClassProxyWithTarget<IFancyService>(service, new IInterceptor[] { interceptor }); 

     Console.WriteLine(proxy.GetResponse("what?")); 
    } 
} 

然而,當我運行它,我得到了以下異常:

未處理的異常信息:System.ArgumentException:「classToProxy」必須是 類參數名:classToProxy

我錯過了什麼?

+1

如果錯誤出現在'var proxy = generator.CreateClassProxyWithTarget (service,new IInterceptor [] {interceptor});'那麼您引用的一個(至少)接口需要引用一個類。 –

回答

5

錯誤是CreateClassProxyWithTarget需要是一個非接口類的類型。 CreateInterfaceProxyWithTarget使用一個接口。

相關問題