IoC, AOP and more - dependency-injection

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.

Related

.NET IoC container for mid-size ASP.NET MVC

My team plan to start a new project this June. This application tend to used by 2,000 concurrent users. Now we are discussing about technical decision - what IoC container we will use in our project. All members in my team don't have experience with IoC, some of us read and know what it is though. Our requirements are:
Performance - Our management state that IoC may slow down the application and they expect that IoC container we use will not degrade the performance. They also expect the IoC container to have a good performance for little or large or resolver process.
Feature sets - I an my coworkers expect it to has rich feature sets. I don't know at this time what feature we gonna use but I have experience that some component can start easy but can't do something more advance.
Documents or books - I plan to study the IoC we selected by reading from online documents or books.
Work with ASP.NET MVC 4
I've used StructureMap, Autofac and Ninject. They are all very good.
I'd recommend using the CommonServiceLocator [http://commonservicelocator.codeplex.com] as part of your implementation. That way it is easy to change your mind later.
I personally like Autofac the best. It has a good balance of features and simplicity.
Supports Autowiring and assembly scanning
Lifetime Scoping (Such as Singleton or HttpRequest)
Easy to register an implementation to multiple request types
Supports Named or Keyed (named by Enum) registration
It's fast
http://code.google.com/p/autofac/wiki/MvcIntegration
http://nuget.org/packages/Autofac.CommonServiceLocator-unofficial

I am looking for a simple yet practical and robust IOC/DI framework for .net

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.

Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)

I have a solution with two relevant (to this question) projects, and a few others;
Class library with functionality used by several other projects.
ASP.NET MVC application.
My question is basically where I should do IoC with Ninject 2, considering...
The class library needs some DI love, among other things in the repository classes which need web request specific session objects (think Unit of Work).
The MVC app needs DI since with Ninject 2 you basically inherit from NinjectHttpApplication.
Unit tests for the class library need to be aware of this to inject a different set of repositories.
Unit tests for the web app need to be injected for the same reason.
I have painted myself into a mental corner here, because I only saw three options to begin with. DI in the class library, DI in the web app, or both, but there are problems with each:
I can't do DI only in the class library since the MVC app needs to inherit from NinjectHttpApplication to begin with.
I can't do DI only in the MVC app - the class library is used by other libraries, after all, and the MVC app shouldn't know too much about the internals of the library anyway.
I guess this is the only way out I can see: Independent IoC for both projects. The class library and the MVC app each have their own IoC setup and do DI for their stuff without really caring about each other.
Does anyone have some "best practices" or guidelines on how to do something like this? I can't imagine I'm the first person to end up in this situation, and it would sure be nice to know what the "proper" way to do this is...
Thanks!
I don't know NInject, but unless it works vastly different than Windsor, StructureMap etc. the answers tend to stay the same, as there are some common DI patterns. With that in mind:
The first thing to realize is that DI isn't tied to a particular framework such as NInject or Windsor. It is a set of techniques and design patterns to follow. You can do DI manually using so-called Poor Man's DI, but obviously it gets much better with a DI Container.
Why is this relevant? It is relevant because once you realize this, the corollary is that the vast majority of your application's code should have no knowledge of the DI Container whatsover.
So where do you use the DI Container? It should only be used in a Composition Root, which in your case would correspond to Global.asax. You can read a bit more about this in this SO answer - although that question is about Windsor, the principle remains the same.
How about your unit tests then? They should be completely ignorant of the DI Container as well. See this other SO answer for more details.
DI can be achieved in your library with copious use of Constructor Injection. You don't need to reference any DI Container to do that, but it makes life a lot easier if you use a DI Container to resolve all dependencies from the Composition Root.

IoC Containers and Domain Driven Design

I've been searching for guidance for using IoC containers in domain driven design. Evan's book unfortunately doesn't touch on the subject. The only substantial guidelines I could find on the internet is here.
Many of Malovic's points are common sense but I'm concerned about a few of them. He suggests that IoC container's should be reserved for resolving services only and that using an IoC container to resolve domain dependencies is a bad idea. However, he doesn't back up this assertion with any examples. He simple states it as a matter of fact.
He then goes on to say that mixing IoC containers and factories doesn't make sense. This appears to contradict his first point. If, in fact, domain dependencies shouldn't be resolved by an IoC container how then should they be resolved? Evan's book clearly points to factories as the logical choice.
I would appreciate any input you have on the matter. I'm a novice when it comes to both DDD and IoC. I'm struggling to grasp how IoC and DDD can work together.
In my opinion he is correct about not using IoC container in domain model. That practice I follow myself as well. Basic idea is that services may contain infrastructure dependencies and therefore its wise to mock them. Domain entities don't have those, so its not important to mock them up (still coding to interfaces is good practice).
Factories for domain entities should not be in IoC container, but factories for services should. Basically you may reference entity factories in your services. It's not very tight coupling.
Good reading about IoC can be found at Billy McCafferty's blog post "Dependency Injection 101"
IOC containers are invaluable when designing unit-testable code and are orthogonal to DDD. You could create your own implementation of factory and builder patterns if you want...by why go through the trouble?
Absolutely. Use an IOC container that's just powerful enough to meet you specific requirements; no more, no less.
We use DDD, and dependency injection (the pattern), but do not use a dependency injection framework.
One problem with popular dependency injection frameworks is how they separate configuration into XML files. XML is a great markup language. How it became a configuration language, I will never understand. The issue, of course, is that you have to run the application before you know if everything is wired up correctly. It is also hard to see what code is used where. If you are using interfaces, then the only reference to an implementation will be in an XML file, which is harder to spot. And finally you lose type safety and generics. (I once saw a horrible bug in production which would have been caught by the compiler had we not been using XML.)
I should point out that I am not saying that dependency injection is bad. It is a fundamental pattern of good object design. But there is absolutely nothing wrong with doing wiring in a factory.
At my last two projects we have removed large amounts of "code" out of XML files, and into factories. The factories are wired up with container managed services (such as JDBC connections, JMS connections and so forth). The application has become much simpler to understand, because the factory is less verbose than XML. And as a Java programmer, it is much easier to wire together a program using control-space, instead of XML twiddling - and your IDE will highlight when you have broken something.
In an integration test, just create the objects as you would in a factory.
ie,
dbConnection = DatabaseConnectionFactory.connection();
serviceUnderTest = new PaymentProcessor(new CustomerRepository(connection));

Which patterns for loose coupling do you use most? [closed]

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.

Resources