Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 487
Alexander Beletsky Avatar asked Jan 18 '12 13:01

Alexander Beletsky


People also ask

What is ninject dependency injection?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.

Which decorator is used for dependency injection?

The @Injectable decorator should be added to each of the services. The @Injectable decorator should be added to any service that uses dependency injection (DI). The @Injectable decorator is not compulsory to add if you don't use the 'providedIn' option.

What is ninject DLL?

Ninject helps you use the technique of dependency injection to break your applications into loosely-coupled, highly-cohesive components, and then glue them back together in a flexible manner.

How does dependency injection work?

Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation. This helps you to follow SOLID's dependency inversion and single responsibility principles.


1 Answers

Use WhenInjectedInto:

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

See this blog post for more info.

like image 100
Daniel Hilgarth Avatar answered Oct 05 '22 11:10

Daniel Hilgarth