2010-06-17 23 views
1

我在Silverlight應用程序中使用Ninject作爲DI容器。現在我正在擴展應用程序以支持攔截並開始爲Ninject集成DynamicProxy2擴展。我試圖攔截對ViewModel屬性的調用,並最終得到以下異常:在Silverlight應用程序中發佈攔截屬性

「試圖訪問該方法失敗:System.Reflection.Emit.DynamicMethod..ctor(System.String,System.Type,System .Type [],System.Reflection.Module,Boolean)「

調用invocation.Proceed()方法時會引發此異常。我試圖攔截的兩個實現,他們都失敗

public class NotifyPropertyChangedInterceptor: SimpleInterceptor 
{ 
    protected override void AfterInvoke(IInvocation invocation) 
    { 
     var model = (IAutoNotifyPropertyChanged)invocation.Request.Proxy; 
     model.OnPropertyChanged(invocation.Request.Method.Name.Substring("set_".Length)); 
    } 
} 

public class NotifyPropertyChangedInterceptor: IInterceptor 
{ 
    public void Intercept(IInvocation invocation) 
    { 
     invocation.Proceed(); 
     var model = (IAutoNotifyPropertyChanged)invocation.Request.Proxy; 
     model.OnPropertyChanged(invocation.Request.Method.Name.Substring("set_".Length)); 
    } 
} 

我想,當屬性值設置爲來電OnPropertyChanged方法的視圖模型。

我正在使用基於屬性的攔截。

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 
public class NotifyPropertyChangedAttribute : InterceptAttribute 
{ 
    public override IInterceptor CreateInterceptor(IProxyRequest request) 
    { 
     if(request.Method.Name.StartsWith("set_")) 
      return request.Context.Kernel.Get<NotifyPropertyChangedInterceptor>(); 

     return null; 
    } 
} 

我用控制檯應用程序測試了實現,它工作正常。

我也注意到在控制檯應用程序中,只要我有Ninject.Extensions.Interception.DynamicProxy2.dll在與Ninject.dll相同的文件夾中我不必顯式加載DynamicProxy2Module到內核中,因爲我必須顯式加載它的Silverlight應用程序如下:

IKernel kernel = new StandardKernel(new DIModules(), new DynamicProxy2Module()); 

可能有人請幫忙嗎?謝謝

回答

0

由於安全問題,Silverlight中的反射會非常棘手。

檢查Gabe的爲this question的答案,這是同樣的問題。

好消息是,您可以使用動態代替代理來實現相同的功能。只需從DynamicObject擴展您的ViewModel並覆蓋TrySetMember方法。我希望它有幫助:)