Ninject and Decorators

Given:

public interface IBatchProcess
{
    void Run();
}

and multiple implementation:

public class BatchProcessOne : IBatchProcess { ... }
public class BatchProcessTwo : IBatchProcess { ... }
public class BatchProcessThree : IBatchProcess { ... }

and trace decoder:

public class BatchProcessTraceDecorator : IBatchProcess
{
    private readonly IBatchProcess _inner;

    public BatchProcessTraceDecorator( IBatchProcess inner )
    {
        _inner = inner;
    }

    public void Run()
    {
        Trace.TraceInformation( "Starting batch process..." );
        _inner.Run();
        Trace.TraceInformation( "Batch process complete." );
    }
}

How can I bind the decorator and all implementations in such a way that when I call kernel.GetAll, I get 3 instances of the trace decorator, each of which has a separate internal batch process?

I know about Ninject interception and do not want to use proxy-based solutions for this for various reasons. At the moment, it seems to me that I need to play with the activation strategy for IBatchProcess instances so that they are allowed, and then I can decorate and return them, but I hope that I just missed something in the api binding.

+5
source share
1 answer

, . OnActivation.

Bind<IBatchProcess>().To<ConcreteBatchProcess>()
                     .OnActivation((ctx, process) => 
                         new BatchProcessDecorator(process));

, ,

Bind<IBatchProcess>().To<ConcreteBatchProcess>()
                     .OnActivation((ctx, process) => 
                         ctx.Kernel.Get<BatchProcessDecorator>(new ConstructorArgument("process", process)));

,

+3

All Articles