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?
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.
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.
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.
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.
Use WhenInjectedInto
:
Bind<IRepository>().To<MoreAdvancedRespository> .WhenInjectedInto<TrickyRepository>(); Bind<IRepository>().To<SomeSimpleRepository> .WhenInjectedInto<MoreAdvancedRespository>();
See this blog post for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With