Friday, August 07, 2009

IOC Containers

I know I haven't blogged lately. I have been well busy with other things but now have some time.

I am at a new client and was brought on the project mid stream. I was talking with the "Boss" about unit testing and how some of the application is tightly coupled and how that makes testing a little tough. He mentioned to me that he as planning on introducing some decoupling in the back ends and somehow we got to talking about IOC Containers.

I started talking about StructureMap and he saw value of an IOC Container framework. He asked me to build a prototype, that was a little more advanced than the basic example you see on line using StructureMap, Unity, and CastleWindsor.

I know all the Spring.Net people are going crazy now because we decided not to use spring without even comparing it, but sorry, I have used spring and I already know I like StructureMap better. Since I havent used the other tools, they were included.

The prototype was an n-tier app that used in the ui. It had a service and datalayer. the idea was using the same interfaces and services, set up the three containers, turn one on run the app, turn another one on run the app, and so on.

The only changes to the app were in the global.asa file, where we build the containers and setting the controller factory.

So lets talk container setup. I felt the setup was pretty easy with windsor and StructureMap. Unity was a little tougher because setting things like default constructers and life management was not as clear. Luckily there was a wealth of information on the internet for how to do these things. The one thing that I really like about StructureMap is on the container you can call a method to assert that the container is valid. If it fails, it gives you a very clear error message explaing why it was not valid. you can have this check and at runtime it will throw, but better practice is just to wrtie a unit test for this. Unity when set up wrong gave me an error at runtime that was hard to understand and I had to parse throught the error about 2/3 of the way through to find out what item was causing the trouble.

As far as using the containers Unity and Windsor dont give you a static object to get your items like StructureMap does with it's ObjectFactory class. You have to manage the access to Unity and Windsor yourself. That said some will argue that if you use Unity or Windsor you would use it with the CommonServiceLocator library. This library will actually handle the container for you.

After showing the "Boss" the protorype and differences he decided to go with StructureMap. Like I told him any of the three would have worked for us, but StrucutreMap's use of Lamdas, and the added auto mocking features won him over.

Post a Comment