Given:
public interface IBatchProcess
{
void Run();
}
and multiple implementation of:
public class BatchProcessOne : IBatchProcess { ... }
public class BatchProcessTwo : IBatchProcess { ... }
public class BatchProcessThree : IBatchProcess { ... }
and a tracing decorator:
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 of the implementations such that when I call kernel.GetAll I get 3 instances of the tracing decorator, each with a different inner 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 looks like I need to play around with the activation strategy for IBatchProcess instances such that they are resolved and then I can decorate and return them but I am hoping I have simply missed something in the binding api.
If you don't need to inject dependencies into the decorator there is a very simple solution to your problem. Simply use the OnActivation binding methods. That would look like
Bind<IBatchProcess>().To<ConcreteBatchProcess>()
.OnActivation((ctx, process) =>
new BatchProcessDecorator(process));
If you need to inject stuff into the decorator you can use the same trick but resolve the decorator by
Bind<IBatchProcess>().To<ConcreteBatchProcess>()
.OnActivation((ctx, process) =>
ctx.Kernel.Get<BatchProcessDecorator>(new ConstructorArgument("process", process)));
Hope that helps