.netinversion-of-controlninjectdecorator

Ninject dependency injection with Decorator pattern


Say, I have such classes hierarchy:

public interface IRepository { }

public class SomeSimpleRepository : IRepository {}

Now I want to "decorate" SomeSimpleRepository with additional functions

public class MoreAdvancedRespository : IRepository 
{ 
    private readonly IRepository _originalRepository;

    public MoreAdvancedRespository(IRepository original) 
    { }
}

After awhile another one..

public class TrickyRepository : IRepository
{
    private readonly IRepository _originalRepository;

    public TrickyRepository (IRepository original) 
    { }
}

Now, I need to accomplish binding. In application I need the instance of TrickyRepository, to be initialized with MoreAdvancedRespository. So, I need to write something like:

Bind<IRepository>().To<TrickyRepository>.With ??

Here I'm confused, I need somehow to say, take MoreAdvancedRespository but initialize it with SomeSimpleRepository. This is a kind of chain of dependencies that have to be resolved against one interface.

Does any one have suggestion on this?


Solution

  • Use WhenInjectedInto:

    Bind<IRepository>().To<MoreAdvancedRespository>()
                       .WhenInjectedInto<TrickyRepository>();
    Bind<IRepository>().To<SomeSimpleRepository>()
                       .WhenInjectedInto<MoreAdvancedRespository>();
    

    See this blog post for more info.