34

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
  • 12,679
  • 7
  • 55
  • 73
Alexander Beletsky
  • 19,453
  • 9
  • 63
  • 86
  • 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

46

Use WhenInjectedInto:

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

See this blog post for more info.

ADH
  • 2,971
  • 6
  • 34
  • 53
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443