ninjectninject-2ninject.web.mvc

Ninject Decorator not being used


What I am trying to do is wrap a decorator around a command using the following code.

public interface ICommand
{
}

public interface ICommand<T> : ICommand where T : class
{
    void Execute(T args);
}

public class TransactionalCommand<T> : ICommand<T>
    where T : class
{
    private readonly ICommand<T> command;

    public TransactionalCommand(ICommand<T> command)
    {
        this.command = command;
    }

    public void Execute(T args)
    {
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
        {
            this.command.Execute(args);

            scope.Complete();
        }
    }
}

Here is how I am invoking the resolve but i only get back my ChangePasswordCommand without the decoratoration. (Actually it wont event compile on the second Bind)

The ultimate goal is to have this auto-register all my types using this decorator. Any help would be great!

        Bind<ChangePasswordCommand>().To<ChangePasswordCommand>()
            .WhenInjectedInto<TransactionalCommand<ChangePasswordArgs>>();
        Bind<ChangePasswordCommand>().To<TransactionalCommand<ChangePasswordArgs>>()
            .InTransientScope();

        var command = kernel.Get<ChangePasswordCommand>();

Solution

  • You were pretty close. However: when you want to use a decorator you need the decorator to implement the same interface as the command. That's the case here, but you'll also need to resolve that interface (and bind it, too). So here's how it works:

    kernel.Bind<ICommand<ChangePasswordArgs>>().To<ChangePasswordCommand>()
        .WhenInjectedInto<TransactionalCommand<ChangePasswordArgs>>();
    kernel.Bind<ICommand<ChangePasswordArgs>>().To<TransactionalCommand<ChangePasswordArgs>>()
        .InTransientScope();
    
    var command = kernel.Get<ICommand<ChangePasswordArgs>>();