I recently learned about the DI frameworks Guice and Ninject and wanted to use them in some of my new projects.
While I am familiar with general dependency injection concepts and know how to use those frameworks to construct object graphs, I struggle to apply IoC when it comes to dynamic application behavior.
Consider this example:
While it is easy to wire the main window's View to a Presenter/ViewModel and then bind that to the domain logic, I don't understand how to cleanly (in the sense of IoC) achieve the following tasks:
IGreenBoxView
, IRedImageView
<-- JConcreteGreenBoxView
, JConcreteRedImageView
) without using any kind of service locator pattern (e.g. requesting from the IoC again)
JOptionPane
at runtimeI've seen some solutions using abstract factories but honestly didn't fully understand them. It seems that such a solution would lead to exposing some of the (view domain's, presenter domain's, ...) internal types to the construction root and, with that, to the whole world.
So - how do I do it right?
There are basically two types of IOC Containers in Spring: BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients. ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface.
IoC container is a framework for implementing automated dependency injection. It contains object creation for the longer ways to use and injects dependencies within the class.
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application.
You can waste days evaluating IOC containers. The top ones are quite similar. There is not much in this, but the best ones are StructureMap and AutoFac. At SSW we use Autofac on most projects.
If you can reuse the controls then you can do constructor injection where you use them. Otherwise you have to inject a factory:
public interface IControlFactory
{
IGreenBoxView CreateGreenBoxView();
IRedImageView CreateRedImageView();
}
and inject it where you need to create this controls.
The implementation goes to the container configuration. There you can inject the container to the implementation. Some containers provide to implement this factory automatically. e.g., in Ninject:
Bind<IControlFactory>().ToFactory();
See https://github.com/ninject/ninject.extensions.factory/wiki
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