9

Based on this question : Should thoses kind of service go injected in a base class ? (versus static classes).

How the binding would be done with decorators using Ninject ? or any DIContainer ?

public class CachedLoggedRepository : IRepository
{
   public IRepository repository { get; set; }
   void Add();
}

public class CachedRepository : IRepository
{
   public IRepository repository { get; set; }
   void Add();
}

public class Repository : IRepository
{
   void Add();
}
ebram khalil
  • 8,252
  • 7
  • 42
  • 60
Rushino
  • 9,415
  • 16
  • 53
  • 93

1 Answers1

15

You have to use conditional bindings e.g

Bind<IRepository>().To<Repository>().WhenInjectedInto<CachedRopsitory>();
Bind<IRepository>().To<CachedRepository>().WhenInjectedInto<CachedLoggedRepository>();
Bind<IRepository>().To<CachedLoggedRepository>();
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
  • 2
    +1 And in some (much rarer) cases, you might be using a generic-based `TImpl`, in which case you `Bind>().To()` as above - in that case you use a slightly different `.When`... clause which [constrains](https://github.com/ninject/ninject/wiki/Contextual-Binding) based on the base generic type of the concrete type being injected into. Another useful thing to bear in mind is that if you ever find you need something slightly different to whats needed, you get the Ninject source and find in files / static analyze through it to find examples - e.g. look at `WhenInjectedInto` – Ruben Bartelink Dec 10 '11 at 07:57
  • 1
    How can this be done when you want to configure multiple dependencies by convention? – Rookian May 05 '15 at 10:37
  • Exactly what I am looking for. – VivekDev Dec 11 '15 at 02:38
  • For some reason this way didn't work for me (messy monolith application and not familiar with NInject or application; lost the will to live trying to understand it) but had to use `Rebind` like this `Rebind().To();` and then `Bind().To().WhenInjectedInto();` – Ricardo stands with Ukraine Jan 29 '21 at 13:35