I recently published a tool called AutoGen for Castle. You can check it out at Google Code. In essence, it auto-generates factory objects for you and adds them to your container. This is an extremely useful thing to be able to do. I do, however, find it a bit hard to explain, so bear with me.
A relatively good rule of thumb these days is that a class should instantiate objects or do something with objects but never both. Miško Hevery has written a lot of good stuff on this subject, and I don’t propose to mangle his thinking here. Now, if we go back to our old Gang of Four maze construction example, the abstract factory in that case produced objects that were closely related and independent. However, that’s rarely the case these days if only because we design systems to have very few interdependent components. It’s actually much more likely that the objects could have been produced using a DI framework such as StructureMap or Castle.
Now, when you start using dependency injection containers, you seem to end up putting “Resolve” or “GetInstance” all over your code. This is an extremely bad idea, for two principal reasons:
- Calling Resolve is conceptually as bad as calling new
- Your code should not be taking a dependency upon its DI framework.
Now Jeremy Miller wrote an excellent article on the question of libraries taking a dependency upon IoC containers. It’s a known problem and hard to deal with without Microsoft stepping up to the plate. However, typically a your code probably doesn’t need an interface as general as the one Jeremy proposed. That’s only going to be useful for people building frameworks. It’d be better if you could specify your own.
That’s what AutoGen does, it lets you specify an interface (or multiple interfaces) for how you interact with Castle. Anything you like, really. By default a parameter called “key” is the key, and anything else gets passed to the constructor. (Obviously, it uses Castle’s semantics for doing this, there’s not a lot of control there.) It even, if you so wished, allows you implement Jeremy’s interface. That won’t help you with standardization, however.
Ideally, this means that you can actually restrict your interaction with your container to your main method. You only need one call to Resolve/GetInstance: the call that resolves your service class. The rest of your code can now be container-agnostic.
Anyway, if you’re interested, you can take a look here:
http://code.google.com/p/castleautogen/
It depends upon Castle Core, Dynamic Proxy and (obviously) Castle Windsor. The tests are written in NUnit 2.4.
Hi Mauricio, you’ve asked a very good question. Sufficiently good, in fact, that it took me a fair while to answer, so I made it another post:http://www.colourcoding.net/…/…dfactory-facility.aspx
LikeLike