Integrating Castle Windsor and NHibernate with WC. A while ago, I wrote this post about how to integrate Castle Windsor and NHibernate with WCF. Last weekend, I used the WCF integration facility of Castle Windsor to accomplish pretty much the same thing, but with less code. We all want that, now don’t we? As a first step, I created a class that implements the ICallContextInitializer. public class UnitOfWorkContext : ICallContextInitializer { private IUnitOfWork _unitOfWork; public Object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message) { _unitOfWork = UnitOfWork.Start(); return null; } public void AfterInvoke(Object correlationState) { if(_unitOfWork !
= null) { _unitOfWork.Dispose(); _unitOfWork = null; } } } Notice that I’m not using the SessionFactory and Session classes of NHibernate directly. Next an implementation of the IServiceBehavior interface needs to be created in order to apply the UnitOfWork context to the service operations. So far, nothing really new actually. We’re almost done. <! Logging with Castle Windsor, the Logging Facility and log4net - A discussion on the altdotnet list just came up around logging. After some various suggestions, I asked what was wrong with using optional dependencies and the built in logging facility in Castle Windsor.
It seemed the most obvious answer Of course, I completely forgot that when I first tried to figure this one out, it had me a little stumped and I took a while to find a good example of it. So here is how it happens. Optional Dependencies in Windsor When you ask the Windsor container for an instance of a class, it goes off and merrily tries to resolve all of the dependencies your class has. This lead to one of the early suggestions on the thread, putting the instance of the Logger as a parameter on the class constructor. But Windsor has a really simple solution to this - optional dependencies. So the first part of the solution to the problem is to put a public property on the class with the logger interface - now Windsor will populate this property if it has a match in the container. The First Spec You Should Write When Using Castle - Fear and Loa.
Thought this might be useful. On a new project where you're using the Castle Windsor container for Dependency Injection, this is a handy spec to have: [ TestFixture ] public class When_starting_the_application : Spec [ Test ] public void verify_Castle_Windsor_mappings_are_correct () IWindsorContainer container = new WindsorContainer ( "castle.xml" ); foreach ( IHandler handler in container . Container . It doesn't guarantee that someone missed adding something to your configuration, but this way anytime someone adds a type to the configuration this will verify the mapping is right. Thanks to the Castle guys for helping me get the simplest syntax going for this.
Container Tutorials - BitterCoder's Wiki.