Ninject. Strange intercept to inner set-properties

安稳与你 提交于 2019-12-02 18:10:11

问题


Domain object:

TargetObject.cs

    public class TargetObject
    {
        public virtual ChildTargetObject ChildTargetObject
        {
            get { return ChildTargetObjectInner; }
            set { ChildTargetObjectInner = value; }
        }

        public virtual ChildTargetObject ChildTargetObjectInner { get; set; }
    }

Configuration and test:

        var settings = new NinjectSettings
        {
            InjectNonPublic = true,
            AllowNullInjection = true
        };
        var kernel = new StandardKernel(settings);

        kernel.Bind<TargetObject>().ToSelf();

        kernel.InterceptReplaceSet<TargetObject>(t => t.ChildTargetObjectInner,
                (inv) =>
                {
                    inv.Proceed();  // <= we never step here. Why?
                }
            );


        var o = kernel.Get<TargetObject>();

        o.ChildTargetObject = new ChildTargetObject();

In the last line we have change property ChildTargetObject and it change inner property ChildTargetObjectInner. But we didnt get interception of it. Why?

If I remove the "virtual" near ChildTargetObject it will be work fine (but this workaround impossible because I use NHiber).

If I change ChildTargetObjectInner directly (ex, o.ChildTargetObjectInner = new ChildTargetObject();), I got intercept.

How can I intercept of any changes (in class and out of class)? Thank you.


回答1:


This is a limitation of the proxying framework and the way ninject creates a proxy.

If you've got a virtual on the method, the method will be proxied/intercepted. however, when you remove the virtual, the method will not be proxied/intercepted anymore.

Now apparently a proxied method making a call to another (proxied) method will not call the proxied method but rather the implementation. So you can't intercept these.

You are probably using castle dynamic proxy. Krzysztof has written a very good tutorial about it, and it also covers virtual and non-virtual methods.

Also note, that since you are using NHibernate, NHibernate will also create proxy. Now when you create a new entity, you may create it through ninject, which will proxy it and configure the interception. However, when you retrieve a persisted entity from the database, it will be created by NHibernate. It will also proxy it and put its interceptors on it. But it doesn't know about ninject's proxies and thus will not add these interceptors. Regarding this, you may want to look into

  • http://nhibernate.info/blog/2008/12/12/entities-behavior-injection.html
  • http://blog.scooletz.com/2011/02/14/nhibernate-interceptor-magic-tricks-pt-3/

Alternatively you could also decorate your methods using Fody MethodDecorator



来源:https://stackoverflow.com/questions/24593289/ninject-strange-intercept-to-inner-set-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!