在Ninject中拦截实例的创建 [英] Intercept creation of instances in Ninject

查看:98
本文介绍了在Ninject中拦截实例的创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望拦截实现某个接口或具有某个属性的实例的创建.我可以做一些与侦听扩展类似的事情,但这似乎只做方法和属性侦听.

I am looking to intercept the creation of instances that implement a certain interface, or have a certain attribute. I am able to do something similiar with the interception extension, but that only seems to do method and property interception.

这是我可以拦截方法和属性调用的方法,但不能拦截构造函数调用:

Here is how I can intercept method and property calls, but it doesn't intercept the constructor call:

_kernel.Bind<IInterceptor>().To<LogInterceptor>().InSingletonScope();
_kernel.Intercept(x =>
{
    if (x.Plan.Type.GetInterface(typeof(ITriggerLoggingInterception).FullName) != null)
    {
        return true;
    }

    return false;
}).With<LogInterceptor>();

推荐答案

正如您自己发现的那样,对于每个绑定,在实例化时最需要做的事情是- IActivationStrategy .

As you found out for yourself, what comes closest to doing something on instanciation for every binding - without requiring the binding to be altered - is an IActivationStrategy.

例如(示例摘自此处:

for example (example taken from here:

public class StartableStrategy : ActivationStrategy
{
  public override void Activate(IContext context, InstanceReference reference)
  {
    reference.IfInstanceIs<IStartable>(x => x.Start());
  }

  public override void Deactivate(IContext context, InstanceReference reference)
  {
    reference.IfInstanceIs<IStartable>(x => x.Stop());
  }
}

通过以下方式添加到ninject内核中:

which is added to the ninject kernel the following way:

kernel.Components.Add<IActivationStrategy, StartableActivationStrategy>();

替代-绑定语法糖

让我更详细地谈谈我在评论中提到的OnActivation()扩展名:

    public static IBindingOnSyntax<T> RegisterEvents<T>(this IBindingOnSyntax<T> binding)
    {
        // todo check whether <T> implements the IHandle<> interface, if not throw exception
        return binding
            .OnActivation((ctx, instance) => ctx.Kernel.Get<EventAggregator>().Subscribe(instance));
    }

您将手动将其用于绑定:

this you would employ manually to the binding:

kernel.Bind<FooViewModel>().ToSelf()
      .RegisterEvents()
      .InSingletonScope();

(不需要InSingletonScope()-只是表明您可以像以前一样使用其他绑定扩展/功能).

(the InSingletonScope() isn't needed - it's just to show that you can use the other binding extensions/features as before).

现在,我认为您想按惯例"使用此功能.如果按约定(ninject.extensions.conventions)创建绑定,则可以使用IBindingGenerator相应地创建绑定(带有或不带有RegisterEvents调用).如果没有,那将变得更加棘手.我说你必须扩展ninject的管道.

Now i think you want to employ this rather "by convention". If you create your bindings by convention (ninject.extensions.conventions), you can use an IBindingGenerator to create the binding accordingly (with or without the call to RegisterEvents). If not, it get's trickier. I'd say you'd have to extend ninject's pipeline.

这篇关于在Ninject中拦截实例的创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆