Downsides of using two IoC containers in same solution in .NET? - c#

I am working on a project which uses a set of libraries from some other developer which uses structuremap as the IoC container. [I have the codebase with me]
The application in which we are incorporating these libraries uses unity container.
Is there a downside to having two container frameworks in the same solution? I want to move everything over to the same IoC container but how do I justify the extra effort?

There is a difference between having multiple container libraries in the same solution vs. the same application, since a solution can consist of multiple runnable applications.
All components should be wired in the application's start-up path, a.k.a. the Composition Root:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
Together with the use of Constructor Injection, the Composition Root pattern keeps your application completely loosely coupled, and keeps your application code decoupled from your DI Container.
According to the Composition Root pattern, no other parts of an application should therefore depend on a DI Container. The fact that the libraries that you use do, is problematic, because this forces you into a certain DI Container. A better solution is to make the libraries DI-friendly.
There are a few downsides to having multiple container libraries in the same solution:
You have to learn two different DI Container libraries, each with their limitations and quirks
Each library comes with its own risk to needing to be replaced when development stops.
On top of that, there are a few downsides to using multiple container libraries in the same application:
Complexities can arise when a single object graph is constructed of application components that come from different containers. It can be hard to visualize object graphs and verify them for correctness.
If some component is resolved from both containers, it could lead to Torn Lifestyles
That's not to say that you should never have multiple containers in the same solution or application. For instance, you could have two containers as a temporary solution, because you are moving from one library to the next, but a big bang migration is too much work. Ideally, you would in that case migrate one application at the time, but even that could be too much to chew off at once.
Another common scenario where having two containers is fine, is when the application framework you are running is using a DI Container internally to build up its services. Common examples of these frameworks are ASP.NET Core and NServiceBus. In that case, to make the distinction clear, I typically talk about the framework's configuration system instead of its internal container, since that's what it basically is. It being a container, is an implementation detail.
In that case you can leave the built-in 'configuration system' as-is to resolve framework components, and use your DI Container of choice to build object graphs of application components.

Related

Singleton Unity Container

I just started getting my head around IOC unity framework. I read couple of articles and videos on MSDN. I have good understanding of how this unity thing works.
1.Create container.
2.Register your interface/classes.
3.Resolve your classes.
I think Steps 1,2 should be abstracted for each project. Is it good idea to create singleton class that creates container and registers interfaces/classes so that unity container will be available in entire project for me to resolve. Please advice.
Except for perhaps a few rare circumstances, you should always have a single container instance for your whole application (app domain). DI containers are thread-safe and are optimized for that scenario. Having multiple containers can cause performance problems and can cause maintenance issues, because some scenarios are very hard to achieve (like having application scoped objects for instance).
Use a singleton. In my current company we are using a singleton wrapper around the Unity container that:
is of course singleton
exposes the most important functionality (like registering and resolve)
takes its configuration from web.config/app.config
but can also be fed at runtime (for instance, for unit testing)
has functionality for default handling in case of unexpected errors during resolve
It works like a charm and makes it easy to focus on the important things.
Don't use a singleton. It encourages you to call resolve all over the place, which is a well-known DI antipattern.
Instead, have a single point in your app (the main function in a desktop app, in the app start function in your web app) where you use the container to resolve your object graph and go from there.
Look at Mark Seeman's discussion of "Composition Root" for more details.

How to use dependency injection in enterprise projects

Imagine you have an application with several hundreds of classes implementing dozens of "high level" interfaces (meaning component level). Is there a recommend way of doing dependecy injection (like with unity). Should there be a "general container" that can be used for bootstrapping, accessible as a Singleton? Should a container be passed around, where all instances can RegisterInstance? Should everything be done by RegisterType somewhere in the startup? How can the container be made accessible when needed. Constructor injection seems false, controverse of being the standard way, you have to pass down interfaces from a component level to the very down where it is used right on startup, or a reference is hold ending up in a "know where you live" antipattern.
And: having a container "available" may bring developers to the idea of resolving server components in client context. how to avoid that?
Any discussion welcome!
edit for clarification
I figured out a somewhat realworld example to have a better picture of what problems i see.
lets imagine the application is a hifi system.
the system has cd player (integrated in a cd-rack) and
an usb port (integrated in an usb rack) to play music from.
now, the cd player and the usb port shall be able to play mp3 music.
i have an mp3 decoder somewhere around, which is injectable.
now i start the hifi system. there is no cd inserted yet and
no usb stick pluged in. i do not need a mp3 decoder now.
but with constructor injection, i have to already inject
the dependency into the cd rack and the usb rack.
what if i never insert a mp3 cd or an mp3 usb stick?
shall i hold an reference in the cd rack, so when an mp3 cd
is inserted, i have a decorder on hand? (seems wrong to me)
the decoder is needed in a subsystem of the cd rack, which
is only started if a mp3 gets inserted. now i have no container
in the cd rack, what about constructor injection here?
First of all, Dependency Injection is a design pattern that does not require a container. The DI pattern states:
Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time
Take for example Guice (java dependency injection framework), in Java Guice is a DI framework but it is not a container itself.
Most of the DI tools in .Net are actually containers, so you need to populate the container in order to be able to inject the dependency
I do not like the idea to have to register every component every time in a container, I simply hate that. There are several tools that help you auto register components based on conventions, I do not use Unity, but I can point you for example to Ninject or AutoFac
I am actually writing a small utility to auto register components based on conventions using practically any DI tool, it is still in dev phase
About your questions:
Should there be a "general container" that can be used for bootstrapping, accessible as a Singleton?
The answer is yes, (there's a tool to abstract the DI tool used, it is called ServiceLocator) that's how DI tools work, there is a static container available to the application, however, it is not recommended to use it inside the domain objects to create instances, that's considered an anti-pattern
BTW I have found this tool really useful to register components at runtime:
http://bootstrapper.codeplex.com/
Should a container be passed around, where all instances can RegisterInstance?
No. that would violate the law of Demeter. If you decide to use a container is better to register the components when the application starts
How can the container be made accessible when needed
Well using the Common Service Locator you could use it anywhere in your application, but like I said, it is not recommended to use it inside the domain objects to create the required instances, instead, inject the objects in the constructor of the object and let the DI tool to automatically inject the correct instance.
Now based on this:
Constructor injection seems false, controverse of being the standard way, you have to pass down interfaces from a component level to the very down where it is used right on startup, or a reference is hold ending up in a "know where you live" antipattern
Makes me think that you are not writing unit tests heavily for your application which is bad. So my suggestion is, before choosing between which DI tool you are going to use, or before taking all the answers you get to this question into consideration, refer to the following links which are focus on one thing: Write clean testable code, this is by far the best source you could get to answer yourself your own question
Clean Code talks:
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
Articles
http://misko.hevery.com/2010/05/26/do-it-yourself-dependency-injection/
http://misko.hevery.com/code-reviewers-guide/
Previous link in PDF http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf
The following links are super highly recommended
http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/
http://www.loosecouplings.com/2011/01/how-to-write-testable-code-overview.html
First, there is the Composition Root pattern, you set up your dependencies as soon as possible, Main() in desktop, global.asax/app_start in web. Then, rely on constructor injection as this makes your dependencies clear.
However, you still need something to actually RESOLVE dependencies. There are at least two approaches known to me.
First one consist in using the Service Locator (which is almost equal to making the container a singleton). This is considered an antipattern for a lot of people, however it just works great. Whenever you need a service, you ask your container for it:
... business code...
var service = ServiceLocator.Current.GetInstance<IMyService>();
service.Foo();
Service Locator just uses a container you set up in the Composition Root.
Another approach consist in relying on object factories available as singletons with the container injected into them:
var service = IMyServiceFactory.Instance.CreateService();
The trick is that implementation of the factory uses the container internally to resolve the service. However, this approach, with an additional factory layer, makes your business code independent and unaware of the IoC! You are free to completely redesign the factories to not to use IoC internally and still maintain every single line of business code.
In other words, it's just a trick then to hide the container/locator behind a factory layer.
While tempted to use the former approach (rely directly on the locator) I prefer the latter. It just feels cleaner.
I wonder if there are other viable alternatives here.
Should a container be passed around
No, since this leads to the Service Locator anti-pattern.
where all instances can RegisterInstance
Services should be registered in the start-up path of the application, not by types themselves. When you have multiple applications (such as web app, web service, WPF client), there will often be a common bootstrapper project that wires all services together for shared layers (but each application will still have its unique wiring, since no application behaves the same).
Should everything be done by RegisterType somewhere in the startup
Yes, you should wire everything up at start-up.
How can the container be made accessible when needed.
You shouldn't. The application should be oblivious to the use of a container (if any container is used, since this is optional). If you don't do this, you will make a lot of things much harder, such as testing. You can however, inject the container in types that are defined in the startup path of the application (a.k.a. the Composition Root). This way the application keeps clean from knowing anything about the container.
Constructor injection seems false, controverse of being the standard way
Constructor injection is the prefered way of injecting dependencies. However, it can be challanging to refactor an existing application towards constructor injection. In **rare* circumstances where constructor injection doesn't work, you can revert to property injection, or when it is impossible to build up the complete object graph, you can inject a factory. When the factory implementation is part of the composition root, you can let it depend on the container.
A pattern I found very useful, that can be built on top of the Dependency Injection pattern and the SOLID design principles, is the command / handler pattern. I found this a useful pattern in smaller apps, but it will shine when applications get big, such as enterprise applications.
now i start the hifi system. there is no cd inserted yet and no usb
stick pluged in. i do not need a mp3 decoder now.
This seems like a perfect fit for Setter injection (=property injection in C#). Use a NeutralDecoder or NullDecoder as a default and inject an Mp3Decoder when you need it. You can do it by hand or using a DI container and conditional/late binding.
http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/
We usually advise people to use constructor injection for all
mandatory collaborators and setter injection for all other properties.

What is the use of spring.net?

We are developing an application using Silverlight and WCF Services. Is using Spring.Net is beneficial for us?
>> "Is using Spring.Net is beneficial for us?"
I think the spirit of your question is really geared more towards questioning the benefit of using an IoC/DI framework versus manually managing dependencies as needed. My response will focus more on the why and why not of IoC/DI and not so much on which specific framework to use.
As Martin Fowler mentioned at a recent conference, DI allows you to separate configuration from usage. For me, thinking about DI in the light of configuration and usage as separate concerns is a great way to start asking the right questions. Is there a need for your application to have multiple configurations for your dependencies? Does your app need the ability to modify behavior by configuration? Keep in mind, this means that dependencies are resolved at runtime and typically require an XML configuration file which is nice because changes can be made without requiring a recompile of the assembly. Personally, I'm not a fan of XML-based configuration of dependencies as they end up being consumed as "magic strings". So there's the danger of introducing runtime errors if you end up misspelling a class name, etc. But if you need the ability to configure on-the-fly, this is probably the best solution today.
On the other hand, there are DI frameworks like Ninject and StructureMap that allow fluent in-code dependency definitions. You lose the ability to change definitions on-the-fly, but you get the added benefit of compile time validations, which I prefer. If all you want from a DI framework is to resolve dependencies then you could eliminate XML-based frameworks from the equation.
From a Silverlight perspective, DI can be used in various ways. The most obvious is to define the relationship of Views to ViewModels. Going deeper, however, you can define validation, and RIA context dependencies, etc. Having all of the dependencies defined in a configuration class keeps the code free from needing to know how to get/create instances and instead focus on usage. Don't forget that the container can manage the lifetime of each object instance based on your config. So if you need to share an instance of a type (e.g. Singleton, ManagedThread, etc.), this is supported by declaring the lifetime scope of each type registered with the container.
I just realized at this point I'm ranting and I apologize. Hope this helps!
Personally i'd recommend using either Castle or Unity as i've had great success with both and found them both, while different, excellent IOC frameworks.
Besides the IOC component they also provide other nifty tools (AOP in Castle, Interface interception in Unity, for example) which you will no doubt find a use for in the future, and having an IOC framework in place from the start is ALWAYS a hell of a lot easier than trying to retrofit it.
It's incredibly easy to setup and configure, although personally i'm not a huge fan of the XML config way of doing things as some of those config files can turn into a total nightmare. A lot of people will tell you that it's only worth doing if you intend to swap components in and out, but why not just do that anyway IN CASE you decide you need to do that later. it's better to have it and not use it, than not have it and need it. If you're worried about perf hit i've seen on many blog posts around the web people comparing the various IOC frameworks for their speed and unless you're creating brain surgery robots or the US Missile defence platform it won't be an issue.
A DI Framework might be of use if you want to change big chunks of your application without having to rewrite your constructors. For example, you might want to use a comet streaming service that you will expose through an interface, and later decide that you'd rather use a dedicated messenging system such as MQ or RendezVous. You will then write an adapter to Mq that respects the common facade and just change the spring config to use the Mq implementation rather than the Comet one.
But for the love of tony the pony, don't use Spring.Net to create your MVVM/MVP/MVC bindings for each and every view or you'll enter a world of pain.
DI is a great tool when used with parcimony, please don't end-up with 243 spring configuration files, for your devs' sanity.
Using an IOC container such as Spring.Net is beneficial as it will enable you to unit test parts of your UI by swapping in mocked or special test implementations of the applications interfaces. In the long run, this should make your application more maintainable for future developers.
I think if you do more in the code rather than using the markup to do bindings etc. and have a BAL/DAL DI can help there because it can inject the correct business component reference (as one example). DI has many other practical advantages, but then you have to do more in code and less in markup.

When would you use the Common Service Locator?

I've been looking at the Common Service Locator as a way of abstracting my IoC container but I've been noticing that some people are strongly against this type of this.
Do people recommend never using it? Always using it? or sometimes using it?
If sometimes, then in what situations would you use it and what situations would you not use it.
Imagine you are writing library code to be used by 3rd party developers. Your code needs to be able to create service objects that these developers provide. However you don’t know which IoC container each of your callers will be using.
The Common Service Locator lets you cope with the above without forcing a given IoC on your users.
Within your library itself you may wish to register your own classes in the IoC, now it gets a lot harder as you need to choose a IoC for your own use that will not get in the way of your callers.
I noticed that one of the arguments against using the CSL is a false one, because developers think this library is only capable of doing the Service Locator pattern. This however isn't the case, because it is easy to use it with the Dependency Injection pattern as well.
However, the CSL library was specially designed for framework designers who need to allows users to register dependencies. Because the library will be calling the CSL directly, from the framework's perspective we're talking about the SL pattern, hence its name.
As a framework designer however, taking a dependency on the CSL shouldn't be taking lightly. For usability of your framework it is normally much better to have your own DI mechanism. A very common mechanism is to set up dependencies in the configuration file. This pattern is used throughout the whole .NET framework. Almost every dependency can be replaced for another. The .NET provider pattern is built on top of this.
When you, as a framework designer, take a dependency on the CSL, it will be harder for users to use your application. Users will have to configure an IoC container and hook it up to the CSL. However, it is not possible for the framework to validate the configuration as can be done while using the .NET configuration system, which as all kind of validation support in it.
I've done some reading on the service locator concept lately. It is a way of helping to reduce coupling, but requires code coupling to the locator - not the container backing the locator, but the locator itself. It is a tradeoff, but can be beneficial in the right situation.
One situation where it can be helpful is when you have code that does not make use of DI, such as legacy code - I am in this boat now. Pulling in required objects via SL, rather than directly creating them, allows the addition of some abstraction. I see it as an intermediate step between SL and DI/IoC.
If you have library code that is in need of services and this code could be hosted in the context of a larger framework/runtime then the framework / runtime would need to provide a mechanism where you can run some custom code on startup wherein you can initialize your container and register dependencies.
A good example of where CSL can be problematic is when using it in the context of MSCRM. You can have custom business logic executed by registering plugins which the MSCRM framework executes on certain events. The problem you run into is where do you run the registration logic since there is no "startup" event that you can subscribe to for setting up your DI container. Even if you could somehow setup your DI you would need to put the CSL and the DI libraries in the GAC since that is the only way to call out to 3rd party code from a plugin (one more item to add to your deployment checklist).
In scenarios such as this you are better off having your dependencies as constructor parameters that the calling code can initialize as it sees fit( via either constructor injection or manually "newing" up the appropriate interface implementation).

Can anyone explain to me, at length, how to use IOC containers?

I use dependency injection through parameters and constructors extensively. I understand the principle to this degree and am happy with it. On my large projects, I end up with too many dependencies being injected (anything hitting double figures feels to big - I like the term 'macaroni code').
As such, I have been considering IOC containers. I have read a few articles on them and so far I have failed to see the benefit. I can see how it assists in sending groups of related objects or in getting the same type over and over again. I'm not sure how they would help me in my projects where I may have over a hundred classes implementing the same interface, and where I use all of them in varying orders.
So, can anybody point me at some good articles that not only describe the concepts of IOC containers (preferably without hyping one in particular), but also show in detail how they benefit me in this type of project and how they fit into the scope of a large architecture?
I would hope to see some non-language specific stuff but my preferred language if necessary is C#.
Inversion of Control is primarily about dependency management and providing testable code. From a classic approach, if a class has a dependency, the natural tendency is to give the class that has the dependency direct control over managing its dependencies. This usually means the class that has the dependency will 'new' up its dependencies within a constructor or on demand in its methods.
Inversion of Control is just that...it inverts what creates dependencies, externalizing that process and injecting them into the class that has the dependency. Usually, the entity that creates the dependencies is what we call an IoC container, which is responsible for not only creating and injecting dependencies, but also managing their lifetimes, determining their lifestyle (more on this in a sec), and also offering a variety of other capabilities. (This is based on Castle MicroKernel/Windsor, which is my IoC container of choice...its solidly written, very functional, and extensible. Other IoC containers exist that are simpler if you have simpler needs, like Ninject, Microsoft Unity, and Spring.NET.)
Consider that you have an internal application that can be used either in a local context or a remote context. Depending on some detectable factors, your application may need to load up "local" implementations of your services, and in other cases it may need to load up "remote" implementations of your services. If you follow the classic approach, and create your dependencies directly within the class that has those dependencies, then that class will be forced to break two very important rules about software development: Separation of Concerns and Single Responsibility. You cross boundaries of concern because your class is now concerned about both its intrinsic purpose, as well as the concern of determining which dependencies it should create and how. The class is also now responsible for many things, rather than a single thing, and has many reasons to change: its intrinsic purpose changes, the creation process for its dependencies changes, the way it finds remote dependencies changes, what dependencies its dependencies may need, etc.
By inverting your dependency management, you can improve your system architecture and maintain SoC and SR (or, possibly, achieve it when you were previously unable to due to dependencies.) Since an external entity, the IoC container, now controls how your dependencies are created and injected, you can also gain additional capabilities. The container can manage the life cycles of your dependencies, creating and destroying them in more flexible ways that can improve efficiency. You also gain the ability to manage the life styles of your objects. If you have a type of dependency that is created, used, and returned on a very frequent basis, but which have little or no state (say, factories), you can give them a pooled lifestyle, which will tell the container to automatically create an object pool for that particular dependency type. Many lifestyles exist, and a container like Castle Windsor will usually give you the ability to create your own.
The better IoC containers, like Castle Windsor, also provide a lot of extendability. By default, Windsor allows you to create instances of local types. Its possible to create Facilities that extend Windsor's type creation capabilities to dynamically create web service proxies and WCF service hosts on the fly, at runtime, eliminating the need to create them manually or statically with tools like svcutil (this is something I did myself just recently.) Many facilities exist to bring IoC support existing frameworks, like NHibernate, ActiveRecord, etc.
Finally, IoC enforces a style of coding that ensures unit testable code. One of the key factors in making code unit testable is externalizing dependency management. Without the ability to provide alternative (mocked, stubbed, etc.) dependencies, testing a single "unit" of code in isolation is a very difficult task, leaving integration testing the only alternative style of automated testing. Since IoC requires that your classes accept dependencies via injection (by constructor, property, or method), each class is usually, if not always, reduced to a single responsibility of properly separated concern, and fully mockable dependencies.
IoC = better architecture, greater cohesion, improved separation of concerns, classes that are easier to reduce to a single responsibility, easily configurable and interchangeable dependencies (often without requiring a recompilation of your code), flexible dependency life styles and life time management, and unit testable code. IoC is kind of a lifestyle...a philosophy, an approach to solving common problems and meeting critical best practices like SoC and SR.
Even (or rather, particularly) with hundreds of different implementations of a single interface, IoC has a lot to offer. It might take a while to get your head fully wrapped around it, but once you fully understand what IoC is and what it can do for you, you'll never want to do things any other way (except perhaps embedded systems development...)
If you have over a hundred of classes implementing a common interface, an IoC won't help very much, you need a factory.
That way, you may do the following:
public interface IMyInterface{
//...
}
public class Factory{
public static IMyInterface GetObject(string param){
// param is a parameter that will help the Factory decide what object to return
// (that is only an example, there may not be any parameter at all)
}
}
//...
// You do not depend on a particular implementation here
IMyInterface obj = Factory.GetObject("some param");
Inside the factory, you may use an IoC Container to retrieve the objects if you like, but you'll have to register each one of the classes that implement the given interface and associate them to some keys (and use those keys as parameters in GetObject() method).
An IoC is particularly useful when you have to retrieve objects that implement different interfaces:
IMyInteface myObject = Container.GetObject<IMyInterface>();
IMyOtherInterface myOtherObject Container.GetObject<IMyOtherInterface>();
ISomeOtherInterface someOtherObject = Container.GetObject<ISomeOtherInterface>();
See? Only one object to get several different type objects and no keys (the intefaces themselves are the keys). If you need an object to get several different object, but all implementing the same interface, an IoC won't help you very much.
In the past few weeks, I've taken the plunge from dependency-injection only to full-on inversion of control with Castle, so I understand where your question is coming from.
Some reasons why I wouldn't want to use an IOC container:
It's a small project that isn't going to grow that much. If there's a 1:1 relationship between constructors and calls to those constructors, using an IOC container isn't going to reduce the amount of code I have to write. You're not violating "don't repeat yourself" until you're finding yourself copying and pasting the exact same "var myObject = new MyClass(someInjectedDependency)" for a second time.
I may have to adapt existing code to facilitate being loaded into IOC containers. This probably isn't necessary until you get into some of the cooler Aspect-oriented programming features, but if you've forgotten to make a method virtual, sealed off that method's class, and it doesn't implement an interface, and you're uncomfortable making those changes because of existing dependencies, then making the switch isn't quite as appealing.
It adds an additional external dependency to my project -- and to my team. I can convince the rest of my team that structuring their code to allow DI is swell, but I'm currently the only one that knows how to work with Castle. On smaller, less complicated projects, this isn't going to be an issue. For the larger projects (that, ironically, would reap the most benefit from IOC containers), if I can't evangelize using an IOC container well enough, going maverick on my team isn't going to help anybody.
Some of the reasons why I wouldn't want to go back to plain DI:
I can add or take away logging to any number of my classes, without adding any sort of trace or logging statement. Having the ability for my classes to become interwoven with additional functionality without changing those classes, is extremely powerful. For example:
Logging: http://ayende.com/Blog/archive/2008/07/31/Logging--the-AOP-way.aspx
Transactions: http://www.codeproject.com/KB/architecture/introducingcastle.aspx (skip down to the Transaction section)
Castle, at least, is so helpful when wiring up classes to dependencies, that it would be painful to go back.
For example, missing a dependency with Castle:
"Can't create component 'MyClass' as
it has dependencies to be satisfied.
Service is waiting for the following
dependencies:
Services:
- IMyService which was not registered."
Missing a dependency without Castle:
Object reference is not set to an
instance of an object
Dead Last: The ability to swap injected services at runtime, by editing an Xml File. My perception is that this is the most tauted feature, but I see it as merely icing on the cake. I'd rather wire up all my services in code, but I'm sure I'll run into a headache in the future where my mind will be changed on this.
I will admit that -- being a newbie to IOC and Castle -- I'm probably only scratching the surface, but so far, I genuinely like what I see. I feel like the last few projects I've built with it are genuinely capable of reacting to the unpredictable changes that arise from day to day at my company, a feeling I've never quite had before.
Try these:
http://www.martinfowler.com/articles/injection.html
http://msdn.microsoft.com/en-us/library/aa973811.aspx
I have no links but can provide you with an example:
You have a web controller that needs to call a service which has a data access layer.
Now, I take it in your code you are constructing these objects your self at compile time. You are using a decent design pattern, but if you ever need to change the implementation of say the dao, you have to go into you code and remove the code that sets this dependency up, recompile / test/ deploy. But if you were to use a IOC container you would just change the class in the configuration and restart the application.
Jeremy Frey misses one of the biggest reasons for using an IOC container: it makes your code easier to mock and test.
Encouraging the use of interfaces has lots of other nice benefits: better layering, easier to dynamically generate proxies for things like declarative transactions, aspect-oriented programming and remoting.
If you think IOC is only good for replacing calls to "new", you don't get it.
IoC containers usually do the dependency injections which in some projects are not a big deal , but some of the frameworks that provide IoC containers offer other services that make it worth to use them.
Castle for example has a complete list of services besides an IoC container.Dynamic proxies ,Transaction management and NHibernate facilities are some of them.
Then I think you should consider IoC contianers as a part of an application framework.
Here's why I use an IoC container:
1.Writing unit tests will be easier .Actually you write different configurations to do different things
2.Adding different plugins for different scenarios(for different customers for example)
3.Intercepting classes to add different aspects to our code.
4.Since we are using NHibernate ,Transaction management and NHibernate facilites of Castle are very helpful in developing and maintaining our code .
It's like every technical aspects of our application is handled using an application framework and we have time to think about what customers really want.

Categories

Resources