I like dagger2 a lot and want to use it in my new project. The only gotcha is with dagger2 we still have to write some boilerplate code and its missing support for CDI.
Since Google is developing and maintaining dagger2 and also using it for their Android development, I am wondering if they are thinking of replacing the DI implementation in Guice with dagger2, which is my first question.
If they are, then I can start using guice expecting that with some future update I will get the goodness of dagger.
But if they are not, is there a way that I can use both in the same project where guice can be limited to CDI.
I'm not a Dagger expert, but I'll try to answer your question... (and I hope to do it well)
I am wondering if they are thinking of replacing the DI implementation in Guice with dagger2,
Nope. There is no good reason to do it. Dagger and Guice present totally different approach to the Dependency Injection concept. The former uses a code generation, the latter - runtime reflection.
(...) is there a way that I can use both in the same project where guice can be limited to CDI?
I don't think it's a good idea to mix CDI, Dagger and Guice in the same project. Beside fact, that CDI is only a specification, not an actual implementation like Weld or OpenWebBeans - so I guess you wanted to say "DI"?.
Anyway: there is dagger-adapter extension which allows using Dagger2 modules with Guice (using DaggerAdapter) if you really want to mix Dagger with Guice 4.
By the way, I would like to give you an idea of what Dagger is and what it never will be. Below is a quote from Christian Gruber (who worked on Dagger) on this subject:
Guice will always have a superset of features compared to Dagger, though we do have projects using Dagger on the server and in stand-alone java apps. But Dagger is not as evolved in terms of the surrounding "scaffolding" code (servlet support, etc.) as Guice, and won’t be for quite some time. Additionally, some teams will need or want some advanced Guice features that will never make it in to Dagger.
You may ask what are these "advanced features"? It is e.g. AOP support, like intercepting methods, which might be crucial for many developers.
You can read the whole discussion (February 2014) which is available here.
As someone working on Java application framework development at Google, I can assure you that Google has large important projects built both with Guice and with Dagger, and both DI systems will continue to be used and developed for the foreseeable future.
My personal idea (which is not an official Google plan or statement) is that over time we will build both more powerful abstractions on top of Dagger (likely in add-on frameworks and/or libraries) so that Dagger continues to become suitable for a larger and larger set of applications, and also more powerful tooling around Guice to make the Guice developer experience become more and more comparable to the Dagger developer experience, at least for a subset of Guice applications that are doing "normal" things.
Both Dagger and Guice are useful tools, each with a different set of trade-offs and a different target audience. Using both in the same project is something that should be possible, although that isn't really the ideal solution because then you can't fully take advantage of the strengths of either of them. But better interoperability is a goal, and the Guice and Dagger teams regularly communicate about how to standardize and coordinate efforts.
Stumbled upon this after having issues with Guice and Java 11. As we barely use guice anyway, I intend to rip it out in favor of dagger for now. Guice is giving me a mega complicated asm based exception that is buried, hard to get a RCA read on and apparently not addressed by the framework. I also, having stepped through the guice code trying to figure this out over a week or so, find the "scaffolding" to be too much for at least my use case and it has me questioning the merits of DI frameworks generally. Dagger2 at least operates at compile time.
Related
What is DI for and what is its use case, when we have ServiceManager?
They appear to be similar since in configuration files for both zend-di and zend-servicemanager we can set up some options such as aliases and invokables.
I am trying to get a better understanding of what is happening behind the scenes with these components, and documentation did not give me enough info.
Could you please tell me what the difference is and when I should use Di instead of ServiceManager?
Zend\DI relies on magic, like reflections, to detect and inject dependencies while service manager uses user provided factories. That is main difference.
Di sort of deprecated in community in favor of SM due to complexity, debugging and performance issues.
It supposed to be good for RAD, but you need above average knowledge to use it properly.
On the other hand SM have pretty verbose and explicit wiring, you can open your code year later and easily figure out what is going on.
Zend\Di takes care of wiring your classes together, whereas with Zend\ServiceManager you have to wire things manually and write a factory closure for every class you want to instantiate.
Zend\ServiceManager is much faster since it does not rely on the slow Reflection API. On the other hand, writing closures for large applications with hundreds of classes becomes very tedious. Keeping your closures up-to-date will get trickier as your application grows.
To address this problem, I have written a Zend Framework 2 module called ZendDiCompiler. It relies on Zend\Di to scan your code and auto-generates factory code to instantiate your classes. You get the best of both components: the power of Zend\Di and the performance of Zend\ServiceManager.
I have put quite a bit of work into the documentation of ZendDiCompiler and some easy and more advanced usage examples are provided, too.
Basically the difference is as follows:
Zend\ZerviceManager = Factory driven IoC Container
Zend\Di = Autowiring IoC implementation
Zend\Di was Refactored for Version 3. Its behaviour now more solid and predictable than v2 and it is designed to integrate seamlessly into zend-servicemanager to provide auto-wiring capabilities (no more odd magic). Since it uses PHP's reflection api to resolve dependencies it is slower than a factory driven approach. Therefore version 3 comes with an AoT compiler to create a pre-resolved Injector that omits the use of Reflection. An additional benefit: The generated factories can also be used with Zend\ServiceManager directly.
There is a guide for using AoT with both components: https://zendframework.github.io/zend-di/cookbook/aot-guide/
When writing object-oriented software, I use dependency injection a lot:
to compose together high-level functionality from lower-level capabilities: my account management service uses repositories and validation services rather than implementing them itself.
to isolate components from their dependencies: my account management service uses its dependencies through interfaces, so that I can swap implementations, mock for unit testing and so on.
What patterns exist in functional programming languages to achieve these goals?
edit: a commenter rightly asks: "what about just passing round functions?". I think that the following comment about function grouping hits the nail on the head - a service is a collection of functions with a shared set of dependencies that I can handle as an atomic group.
In Clojure it seems like protocols solve this nicely, but I was really wondering how the problem is solved more generally...
Some time ago I've read a post describing how dependency injection can be seen as currying in functional programming. I think it's very interesting, and it gives a good perspective on the topic.
At the small scale, things like currying and functions-as-parameters cut down the need for module dependencies. At a larger scale, things like Standard ML functors are very useful for this purpose. Racket has a system called units that does a good job on this too.
I developed a little library which I found helpful for DI in a functional-inspired (JavaScript) environment, it's nothing special, just a bit method I like.
I am going to use it in a project with less-experienced developers so a complex framework such as Spring.NET is not an option. I was thinking about:
Ninject
Castle Windsor
StructureMap
Which would present a moderate learning curve without losing flexibility?
and another question - where is the correct place to put the configuration? Since the kernel/configuration on a 3-tier ASP.NET application (not MVC!!! all examples are using MVC :) )
The great thing about proper use of DI is that you can defer the decision about which DI Container to use until the last responsible moment. In application architecture terms, this corresponds to a so-called Composition Root, which is where you wire all depedendencies together. This is often the application's entry point.
Apart from the Composition Root, the entire application can be written without referencing any particular DI Container at all. You just need to follow well-known patterns and principles.
When it comes to pick a DI Container, I'm aware of these DI Containers for .NET:
Castle Windsor
StructureMap
Unity
Autofac
Ninject
Spring.NET
Personally, I have been happy with Castle Windsor so far, but I have yet to gain extensive experience with all of these containers.
Here's an ASP.NET (not MVC) Ninject sample:
http://davidhayden.com/blog/dave/archive/2008/06/20/NinjectDependencyInjectionASPNETWebPagesSample.aspx
I have used ninject and found it easy to bring new developers up to speed with it.
Consider to start with wiring by hand: see http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion . It gives less-experienced developers a better insight in the basics of IOC/DI.
I think you are being too hasty to reject spring.net. Spring offers an extremely flexible learning curve, so at the beginning it's kind of "you take what you want from it" approach.
You can start with the simplest-of-all IoC container, and later on move to aop, transactions, unit testing, or whatever you desire, so the complexity builds up gradually.
This was the #1 selling point at my last two jobs for using Spring. Additional points were:
It doesn't force you to use its api or to bend your architecture. Again, this leads you to adapt its features at your own pace.
Very extensive documentation.
When the project matures, so will your developers, so spring will come out handy at the end ... (at no cost in the beginning, in my opinion)
Autofac is my container of choice. It allows registration via lambda expressions for maximum flexibility (the link has some nice examples).
It also has a Silverlight-compatible version. I'm unsure if the other containers do.
As for placement, the container should be built during application startup. For an ASP.NET application, this would be in the Global.Application_Start method.
Autofac has ASP.NET integration which injects pages instances using the container you build during startup.
Have a look at http://funq.codeplex.com/ first of all it's extremely fast compared to windsor and other reflection based containers second of all it's very flexible but still has a very readable configuration (If you've gotten your head around Lamba expressions which should take to long any ways)
We use the managed extensibility framework. It is part of the .NET 4.0 framework (currently in release candidate), where you can find it in the System.ComponentModel.Composition namespace. The codeplex site is currently still the best source of documentation.
The focus of MEF is more on "extensibility" rather than "dependency injection", but it uses dependency injection to achieve this. For example, the visual studio 2010 code editor uses MEF to enable extensibility.
We use it as a DI framework and have not yet run into any problems (though I did need the dynamic instantiation sample which is not part of the core yet).
If you're yet familiar with any DI framework, I'd go with the Simple Injector.
It has a very simple API, that will get you started very quickly. Although simple, it still enables many advanced configuration scenario's. The library designed with migration in mind, which means that switching to another framework would is rather straightforward. To prove this point, there is an migration guide on the project's wiki.
In addition to Ninject, which is a great product, there are also two other options that I'm familiar with:
Microsoft's Unity. Some Alt.NET folks think it's a little on the big & complicated side. I've been using it for several months now as part of Prism (Prism is NOT required to use Unity. It's available stand-alone) and I've found it to be simple and straight-forward.
StructureMap. I've found StructureMap to also have a very gentle learning curve with fast ramp up.
Hope this helps.
I find StructureMap very usefull and intuitive to use. I played with Ninject a bit and found that less convenient, but YMMV. I would also recommend you use the common service locator as an intermediary between the actual implementation of your IOC and your application. When you want to switch your IOC/DI container later on, this is less painfull. There are adapters for StructureMap and Castle windsor. And I think from googling that there also is an adapter for Ninject 2 according to this blog.
What is an IoC container?
What is an IoC/DI framework?
Why do we need a framework for IoC/DI?
Is there any relationship between IoC/DI and AOP?
What is Spring.net/ninject with respect to IoC and AOP?
JMSA,
James Kovacs wrote a fantastic article which covers many of your questions I would recommend reading it Here
Spring.Net, Ninject, Unity, Castle Windsor, Autofac are all IOC containers which are configurable in different ways, many of them do also support AOP.
Frameworks for IOC/DI are useful because they provide standard mechanisms, for example if you are hiring a new developer it is much easier to say, we use this framework and pass them the links to the tutorials / help guide. At the same time these frameworks are tried and tested by a large community / companies.
Let me know if any of your questions remain unanswered after reading the article and the above answes and I'll do my best to provide further assistance.
From a semantics point of view...
Dependency Injection itself implies a dependency, i.e. something that is required for construction/use (the application's "core concerns"). For example, a car is not a car without an engine.
Aspects are described as being cross-cutting to the application's core concerns. That means both separate from and non-crucial to the core concerns (you could think of them as "nice-to-haves"). Since the application can run without aspects, are they really dependencies? For example, a car is still a car even without an immobiliser.
(Of course, this is from a theoretical standpoint. In the real world matters like security are often as crucial to the existence of a marketable product as the core concerns themselves.)
So in while in practice DI can be used to implement aspects, I would not call that process true DI. This is coming from someone who uses constructor injection exclusively.
Martin Fowler has a good article here on the meaning of Inversion of Control and Dependency Injection.
Spring.NET usage AOP is described in detail here. I'm more familiar with the Java-based version of Spring, so I cannot say with absolutely certainty that Spring.NET currently only supports proxy-based AOP.
That is, a class to be advised must implement an interface. Spring will create a dynamic proxy that implements this interface and delegates to the original target instance.
Although it does state:
In a future release we will implement proxies using inheritance, which will allow you to proxy classes without interfaces as well and will remove some of the remaining raw reference issues that cannot be solved using composition-based proxies.
I absolutely need to use an IoC container for decoupling dependencies in an ever increasingly complex system of enterprise services. The issue I am facing is one related to configuration (a.k.a. registration). We currently have 4 different environments -- development to production and in between. These environments have numerous configurations that slightly vary from environment to environment; however, in all cases that I can currently think of, dependencies between components do not differ from environment to environment, though I could have missed something and/or this could obviously change.
So, the ultimate question is, does anybody have a similar experience using an IoC framework? Or, can anybody recommend one framework over another that would provide flexible registration be it through some sort of convention or simplified configuration information? Would I still be able to benefit from a fluent interface or am I stuck with XML -- I'd like to avoid XML-hell.
Edit: This is a .Net environment and I have been looking at Windsor, Ninject and Autofac. They all seem to now support both methods of registration (fluent and XML), though Autofac's support for lambda expressions seems to be a little different than the others. Anybody use that in a similar multi-deployment environment?
If you want to abstract your container, and be able to use different ones, look into having it injectable in a way I tried to do it here
I use Ninject. I like the fact that I don't have to use Xml to configure the dependencies. I can just use straight up C# code. There are multiple ways of doing it also. I know other libraries have that feature, but Ninject offers fast instantiation, it is pretty lightweight, it has conditional binding, supports compact framework, and it supports Silverlight, 2.0. I also use a wrapper on top of it, in case I do switch it out for another framework in the future. You should definitely try Ninject when deciding on a framework.
I'm not sure whether it will suit your particular case, you didn't mention what platform you're working in, but I've had great success with Castle Windsor's IOC framework. The dependencies are setup in the config file (it's a .NET framework)
Look at Ayendes rhino commons. He uses an abstraction over the IoC container. So that you can switch containers whenever you want. Something like container.Resolve is always there in every container.
I use Structuremap to do the dirty work it has a fluent interface and the XML things and it is powerfull enough for most things you want to do. Each one has it's own pros and cons so a little abstraction so you can easily switch (you never know how long they are going to be around) is good. For the rest I think Spring.Net, Castle windsor, Ninject and StructureMap aren't that far apart anymore.