Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I decorate all my bindings implementing a specific interface in Ninject

I'm using Jimmy Bogard's Mediatr and trying to use the pipleine example here

my problem is that although I can get all my closing generic types like so

     kernel.Bind(
            x =>
                x.FromAssemblyContaining<ExpensiveRequest>()
                    .SelectAllClasses()
                    .InheritedFrom(typeof (IRequestHandler<,>)).BindAllInterfaces()

I can't decorate them all with the MediatorPipeline.

So if I were using StructureMap I could use something like this

cfg.For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(MediatorPipeline<,>));

I can't find how I would achieve it with Ninject so that when when my Mediator is called it uses the Mediator pipeline and then down to the original Handler

like image 756
Kev Hunter Avatar asked Nov 01 '22 11:11

Kev Hunter


1 Answers

Couple of ways to do this. You can either do a convention based scan which you are already doing, and add a contextual binding to the end of it:

kernel.Bind(x => x.FromAssemblyContaining<ExpensiveRequest>()
     .SelectAllClasses()
     .InheritedFrom(typeof(IRequestHandler<,>))
     .BindAllInterfaces();
     .Configure(c => c.WhenInjectedExactlyInto(typeof(MediatorPipeline<,>));

Then just do the exact same thing again without the WhenInjectedExactlyInto context filter:

kernel.Bind(x => x.FromAssemblyContaining<ExpensiveRequest>()
     .SelectAllClasses()
     .InheritedFrom(typeof(IRequestHandler<,>))
     .BindAllInterfaces();

This would require two assembly scans to happen though.

Another way would be to write an IBindingGenerator, and perform multiple bindings in there - one with WhenInjectedExactlyInto and another without. This would then only require a single convention based binding using the .BindWith<MyBindingGenerator>() syntax instead of .BindAllInterfaces()

like image 184
AaronHS Avatar answered Jan 04 '23 14:01

AaronHS