33

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?

jruizaranguren
  • 11,153
  • 7
  • 53
  • 70
Alexander Beletsky
  • 18,875
  • 9
  • 60
  • 85
  • 1
    possible duplicate of [How the binding are done with decorators using Ninject?](http://stackoverflow.com/questions/8447037/how-the-binding-are-done-with-decorators-using-ninject) – Ruben Bartelink Apr 05 '12 at 12:12
  • 2
    Possible duplicate of [How the binding are done with decorators using Ninject?](https://stackoverflow.com/questions/8447037/how-the-binding-are-done-with-decorators-using-ninject) – NightOwl888 Mar 09 '18 at 12:54

1 Answers1

45

Use WhenInjectedInto:

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

See this blog post for more info.

Daniel Hilgarth
  • 166,158
  • 40
  • 312
  • 426