2011-06-10 69 views
3

我開始使用Castle DynamicProxy,並且我有這個示例來跟蹤對對象屬性的更改。在.NET web-apps中使用Castle DynamicProxy的性能建議

問題:

  • 我應該緩存(靜態字段)我在AsTrackable使用ProxyGenerator()()的實例?我將在ASP.NET Web應用程序中使用,並且我不確定該類是否是線程安全的?創建是否昂貴?
  • 如果我按原樣保留代碼,生成的代理類型是否會被不同的ProxyGenerator實例重新使用。我讀了caching tutorial,但不確定「模塊範圍」的含義。
  • 從性能的角度來看,有沒有其他建議可以改進代碼?

代碼:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var p = new Person { Name = "Jay" }.AsTrackable(); 

     //here's changed properties list should be empty. 
     var changedProperties = p.GetChangedProperties(); 

     p.Name = "May"; 

     //here's changed properties list should have one item. 
     changedProperties = p.GetChangedProperties(); 
    } 
} 

public static class Ext 
{ 
    public static T AsTrackable<T>(this T instance) where T : class 
    { 
     return new ProxyGenerator().CreateClassProxyWithTarget 
     (
      instance, 
      new PropertyChangeTrackingInterceptor() 
     ); 
    } 

    public static HashSet<string> GetChangedProperties<T>(this T instance) 
    where T : class 
    { 
     var proxy = instance as IProxyTargetAccessor; 

     if (proxy != null) 
     { 
      var interceptor = proxy.GetInterceptors() 
            .Select(i => i as IChangedProperties) 
            .First(); 

      if (interceptor != null) 
      { 
       return interceptor.Properties; 
      } 
     } 

     return new HashSet<string>(); 
    } 
} 

interface IChangedProperties 
{ 
    HashSet<string> Properties { get; } 
} 

public class PropertyChangeTrackingInterceptor : IInterceptor, IChangedProperties 
{ 
    public void Intercept(IInvocation invocation) 
    { 
     invocation.Proceed(); 

     this.Properties.Add(invocation.Method.Name); 
    } 

    private HashSet<string> properties = new HashSet<string>(); 

    public HashSet<string> Properties 
    { 
     get { return this.properties; } 
     private set { this.properties = value; } 
    } 
} 

public class Person 
{ 
    public virtual string Name { get; set; } 
    public virtual int Age { get; set; } 
} 

}

回答

4

它是線程安全的緩存代理生成的靜態副本,你絕對應該這樣做。這被認爲是使用此API的最佳做法,如果不這樣做,則會無緣無故地導致在新動態程序集中定義的額外類型。

相關問題