开发者

Issue intercepting property in Silverlight application

开发者 https://www.devze.com 2023-01-03 14:00 出处:网络
I am using Ninject as DI container in a Silverlight application. Now I am extending the application to support interception and started integrating DynamicProxy2 extension for Ninject. I am trying to

I am using Ninject as DI container in a Silverlight application. Now I am extending the application to support interception and started integrating DynamicProxy2 extension for Ninject. I am trying to intercept call to properties on a ViewModel and ending up getting following exception:

“Attempt to access the method failed: System.Reflection.Emit.DynamicMethod..ctor(System.String, System.Type, System.Type[], System.Reflection.Module, Boolean)”

This exception is thrown when invocation.Proceed() method is called. I tried two implementations of the interceptor and they both fail

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));
    }
}

I want to call OnPropertyChanged method on the ViewModel when property value is set.

I am using Attribute based interception.

[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;
    }
}

I tested the implementation with a Console Application and it works alright.

I also noted in Console Application as long as I had Ninject.Extensions.Interception.DynamicProxy2.dll in same folder as Ninject.dll I did not开发者_如何学编程 have to explicitly load DynamicProxy2Module into the Kernel, where as I had to explicitly load it for Silverlight application as follows:

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

Could someone please help? Thanks


Reflection can be really tricky in silverlight because of security issues.

Check Gabe's answer for this question, it's the same problem.

The good news is that you can achieve the same functionality you want using dynamic instead of proxies. Just extend your ViewModel from DynamicObject and override the TrySetMember method.

I hope it helps :)

0

精彩评论

暂无评论...
验证码 换一张
取 消