Question

J'ai actuellement un problème, en essayant de câbler exactement une instance intercepteurs par une instance de la classe interceptés.

Je crée et conseils dans le InterceptorRegistrationStrategy et le réglage de la fonction de rappel pour résoudre un intercepteur du noyau (il a un constructeur d'injection). S'il vous plaît noter que je ne peux que intercepteur instancier dans le rappel car InterceptorRegistrationStrategy ne pas référence au noyau lui-même.

            IAdvice advice = this.AdviceFactory.Create(methodInfo);
            advice.Callback = ((context) => context.Kernel.Get<MyInterceptor>());
            this.AdviceRegistry.Register(advice);

J'obtiens une instance de intercepteur par méthode.

Est-il possible de créer une instance d'intercepteurs par exemple de type étant interceptées?

Je pensais à named scope, mais le type et interceptées intercepteur ne fait pas référence à l'autre.

Était-ce utile?

La solution

Ce n'est pas possible comme un intercepteur unique est créé par la méthode pour toutes les instances d'une liaison.

Mais ce que vous pouvez faire est de ne pas exécuter le code d'interception directement dans l'intercepteur, mais pour obtenir une instance d'une classe qui va gérer l'interception.

public class LazyCountInterceptor : SimpleInterceptor
{
    private readonly IKernel kernel;

    public LazyCountInterceptor(IKernel kernel)
    {
        this.kernel = kernel;
    }

    protected override void BeforeInvoke(IInvocation invocation)
    {
        this.GetIntercpetor(invocation).BeforeInvoke(invocation);
    }

    protected override void AfterInvoke(IInvocation invocation)
    {
        this.GetIntercpetor(invocation).AfterInvoke(invocation);
    }

    private CountInterceptorImplementation GetIntercpetor(IInvocation invocation)
    {
        return this.kernel.Get<CountInterceptorImplementation>(
            new Parameter("interceptionTarget", new WeakReference(invocation.Request.Target), true));                
    }
}

public class CountInterceptorImplementation
{
    public void BeforeInvoke(IInvocation invocation)
    {
    }

    public void AfterInvoke(IInvocation invocation)
    {
    }
}

kernel.Bind<CountInterceptorImplementation>().ToSelf()
      .InScope(ctx => ((WeakReference)ctx.Parameters.Single(p => p.Name == "interceptionTarget").GetValue(ctx, null)).Target);

Autres conseils

Avez-vous essayé d'utiliser l'API couramment pour configurer votre interception?

Bind<IInterceptor>().To<MyInterceptor>().InSingletonScope();
Bind<IService>().To<Service>().Intercept().With<IInterceptor>();

N.B.. Le procédé d'extension de Intercept() est en Ninject.Extensions.Interception.Infrastructure.Language.ExtensionsForIBindingSyntax

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top