I am confused about this line
Aspect-Oriented Programming and Dependency Injection are very different concepts, but there are limited cases where they fit well together.
from this website
http://www.postsharp.net/blog/post/Aspect-Oriented-Programming-vs-Dependency-Injection
I understand the advantages of DI over AOP, but why aren't they used together more often? why are there only limited cases where they fit together? Is it because of the way AOP is compiled, that makes using both difficult?
How do you define "limited cases"? I myself always use AOP and DI together.
There are basically three ways to apply AOP, which are:
Using code weaving tools such as PostSharp.
Using dynamic interception tools such as Castle Dynamic Proxy.
Using decorators.
The use of DI with code weaving tools doesn't mix and match very well, and I think that's the reason that the Postsharp site states that "there are limited cases where they fit well together". One reason it doesn't mix and match is because Dependency Injection is about loose coupling, while code weaving hard couples your code and the aspects together at compile time. From a perspective of DI, code weaving becomes an anti-pattern. In section 11.2 of our book, Mark and I make this argument very clear. In summary we state:
The aim of DI is to manage Volatile Dependencies by introducing Seams into your application. Theis enables you to centralize the composition of your object graphs inside the Composition Root.
This is the complete opposite of hat you achieve when applying compile-time weaving: is causes Volatile Dependencies to be coupled to your code at compile-time. This makes it impossible to use proper DI techniques and to safely compose complete object graphs in the application's Composition Root. It's for this reason that we say that compile-time weaving is the opposite of DI–using compile-time weaving on Volatile Dependencies is an anti-pattern. [page 355]
If you use dynamic interception, however, which means applying cross-cutting concerns at runtime by generating decorators on the fly it works great with DI and it is integrated easily with most DI libraries out there, and can be done as well when using Pure DI, which is something we demonstrate in section 11.1.
My personal preference is to use decorators. My systems are designed around a few well defined generic abstractions, and this allows me to apply cross-cutting concerns at almost all places that are important to my system. That leaves me in very rare cases with a few spots where decorators don't work very well, but this is almost always caused by design flaws. Either by my own limitations as a developer or by design flaws in the .NET framework or some other tool. One famous design flaw is the INotifyPropertyChanged interface. You might have guessed it, but in our book we describe this method in a lot of detail. We spend a complete chapter (10) on this topic.
Related
I am currently creating a small personal windows (desktop) .NET LOB application and I want to use the opportunity to increase my knowledge and experience with DI. I've separated my application into model, DAO and GUI parts but I am wondering how to implement some cross-cutting concepts such as:
currently logged on user - used for:
asserting rights - in some parts of the application I check if the user has necessary rights
auditing - recording user actions into a separate database table
etc
current application parameters (loaded from configuration file or table) - used for:
defining business strategy
defining UI (theme for example)
etc
logging to file/database log - used for:
logging UI actions (clicking on buttons etc.)
logging business processes (results of calculations, strategy decisions etc.)
logging infrastructure stuff (SQL used to for CRUD operations)
etc
At the moment I can think of several ways to provide this information:
Using static properties - UserEntity.Current, Configuration.Current, Logger.Current, etc.
Pros:
Simple to implement
Simple to use
Cons:
Gets messy
It is unclear which part of the application uses what
Can not be used if you need finer granularity (for example if for some processes in the application you need to override current values)
Using DI - giving each class which needs this information a property/ctor parameter
Pros:
It is clear for each class what it needs
It is easy to unit test
Cons:
It just seems to explode constructors
Makes problems if class needs to have a default constructors
Difficult to setup when classes get instantiated by 3rd party (XAML)
Using ServiceLocator
Pros:
Easy to setup
Easy to use
Cons:
It is unclear which part of the application uses what
Difficult to setup finer granularity (but not impossible)
I am currently leaning towards ServiceLocator as I've worked with it before and it worked quite nice. However I am concerned about loss of control. It gets very easy to just reach for the service locator instead of trying to fix a design problem.
Can somebody provide their experiences/knowledge?
Sounds like perfect case to start with aspect-oriented approach. Your application's LOB will be designed according to business functional requirements that has been cross-cutted with different non-functional requirements: authentication, audit, logging, etc.
In same time, some of current application requirements could be solved by dependency-injection. To start, I recommend first to identify composition root. For example, in wpf applications it’s the Application.OnStartup method. In case if you are able to identify composition root it is better to avoid service-locator. Service locator will add unneeded complexity while maintaining and testing, because it could resolve literally anything, thus dependency management will be complicated.
Next step, to decide: should dependency injection and aspect-oriented approaches be separated or combined. Both approaches has benefits and drawbacks.
While choosing separated approach you could use postsharp with a lot of benefits: great samples and documentation, community and ready to use aspects. But nothing come for free, postsharp has only limited number of features in free version and complicated integration with continues-integration.
Another solution: combine dependency-injection with dynamic-proxy. As long as you follow conception: program to an interface, not an implementation — you will achieve all requirements. Benefits: one place to wire all components. There are two major drawbacks: first dynamic proxy is quite limited itself, second — integration between dependency injection container and dynamic proxy — for some container it already exists, for others not. Example: Ninject extension Interception, or StructureMap and Interception.
I recommend you to take a look at following resources to find more answers yourself:
* Book AOP in .NET: Practical Aspect-Oriented Programming by Matthew D. Groves: first chapter available for free
* Book Dependency Injection in .NET by Mark Seemann: well-written book about dependency injection, and chapter #9 dedicated to interception, approach that I found quite useful in cases that you had described in question. Author of book also has an excellent blog dedicated to dependency injection and video about aspect-oriented programming with dependency Injection.
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.
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.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Lately I have seen a lot of blog posts concerning how to build loosely coupled applications. Which patterns do you use most when creating loosely coupled applications? Dependency Injection? Inversion of Control?
Model-View-Controller.
Aside: things that stops me writing coupled applications aren't just patterns:
Naming. If I can't easily think of a name for my class, it either does nothing or too many things.
Testability. If I can't easily mock out my class' dependencies, it's a coupled design.
I find myself using the Command pattern quite often. It's a pattern that just keeps giving project after project.
Dependency injection with spring is my favourite. Additionally with maven it's common to do this really neat trick of hiding all the implementations behind an API module. So if your code has three modules, "application-core", "externalsystems-api" and "externalsystems", you can make "application-core" depend ONLY on externalsystems-api. The actual-implementations and all their dependencies can be totally invisible to the application-core module. This really enforces a much harder separation of concerns and makes loose coupling easier.
The neat thing is that IDEs that load these maven setups enforce these visibility constraints. So you're not going to be able to reference SQL, AXIS, JAXB or whatever in your application-core
Some of the SOA related patterns (enterprise service bus for example) offer abstraction at a higher level and support separation of concerns across business services and technical services. Loose coupling between the services is then (arguably) supported by introducing a broker or bus that de-couples the services in the solution.
Visitor pattern works quite well
I think one of the fundamental techniques is "Tell Don't Ask Principle, Law Of Demeter". Maybe it is not like DI,UI or other Desing Patterns but I think objects that fallow this principle are loosely coupled and do the one thing well.
"Keep It Shy Keep It Dry Tell The Other Guy"
Yes, the important ones are Dependency Injection and Inversion of Control, but lets not forget the Abstract Factory and Registries.
Bridge pattern (http://en.wikipedia.org/wiki/Bridge_pattern)
Dependency Injection is a form of Inversion-of-control.
The Spring Framework has a large base of Java programmers, and it has a .NET implementation, too.
The Strategy Pattern.
I'm surprised this hasn't been mentioned yet - strategies allow you to avoid creating classes that know too much about different types in your domain model. Each strategy is responsible for codifying a particular interaction involving specific types. This avoids creating a master type that is aware of many others and the nuances of the implementation of each.
From Wikipedia:
The strategy pattern uses composition
instead of inheritance. In the
strategy pattern behaviors are defined
as separate interfaces and specific
classes that implement these
interfaces. Specific classes
encapsulate these interfaces. This
allows better decoupling between the
behavior and the class that uses the
behavior. The behavior can be changed
without breaking the classes that use
it, and the classes can switch between
behaviors by changing the specific
implementation used without requiring
any significant code changes.
Behaviors can also be changed at
run-time as well as at design-time.
Dependency injection and IOC are both excellent for decoupling code.
Dotnetrocks show 362 provides very good definitions. Also watch the related DNR TV episode to get a clearer understanding.
Dependency injection is the pattern that I use in nearly all classes that I write - if the class has a dependency, I always inject it (using constructor injection). Only classes which have no dependencies (i.e. value objects) don't use the DI pattern. Being able to test classes which use DI is a major benefit.
For information on the benefits of DI, these two presentations are very good:
http://googletesting.blogspot.com/2008/11/clean-code-talks-dependency-injection.html
http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html
No DI container is needed to use the DI pattern, but when the program becomes big (tens of classes or many scopes), then a DI container can reduce much boilerplate. On the JVM my default choice is Guice.
Inversion of Control as overall code/architecture style.
DI as a mechanism to configure IoC.
Local abstractions (I call this "Ideal Environment Development" - write as if you had the exact environment you wanted).
Objects typically communicate using void methods, and by passing data, rather than having getters/setters.
I never use a dependency directly in a core business class - it is always abstracted to a local abstraction, and an explicit Bridge deals with the dependency.
I've found that this combination allows for extremely flexible code with a very compositional feel to it.