bling.github.io

This blog has relocated to bling.github.io.
Showing posts with label Castle. Show all posts
Showing posts with label Castle. Show all posts

Saturday, December 11, 2010

Auto Mocking NSubstitute with Castle Windsor

I was debating whether to make this blog post because it’s so damn simple to implement, but hey, if it saves someone else time, I did some good.

First of all, register an ILazyComponentLoader into Windsor:

var c = new WindsorContainer();
c.Register(Component.For<LazyComponentAutoMocker>());

Then, the implementation of LazyComponentAutoMocker is simply this:

public class LazyComponentAutoMocker : ILazyComponentLoader
{
  public IRegistration Load(string key, Type service, IDictionary arguments)
  {
    return Component.For(service).Instance(Substitute.For(new[] { service }, null));
  }
}

And you’re done!  Here’s a simple unit test example using only the code from above:

[Test]
public void IDictionary_Add_Invoked()
{
  var dict = c.Resolve<IDictionary>();
  dict.Add(1, 1);
  dict.Received().Add(1, 1);
}

That was almost too easy.

Friday, May 14, 2010

Contextual Lifestyle with Castle Windsor

EDIT: As of version 3, scoped lifestyles are now a first class citizen supported out of the box (http://docs.castleproject.org/Windsor.Whats-New-In-Windsor-3.ashx)
EDIT: A much better implementation can be found at https://github.com/castleprojectcontrib/Castle.Windsor.Lifestyles

IMO, one of the big missing features of Castle Windsor is that it doesn’t come with a built-in way for dealing with contextual lifestyles.  It handles transients and singletons fairly well, but once you get to other lifestyles it’s pretty heavily dependent on having some “state manager” handling the instances.  For example, PerWebRequest uses the HttpContext, PerThread uses thread static variables, etc.
Contextual lifestyles is one of those things where it doesn’t seem all that useful at first, and then when you see the possibilities it’s like getting hit with a huge truck.
A question was posted to the Castle Google Group recently, which I follow, which illustrates a relatively common example of why someone would want to have a contextual lifestyle.  Basically, you have a whole bunch of components you want to resolve, but only within a context.
Here’s some boiler plate code of the domain model:
public interface IRepository { ISession Session { get; } }
public interface ISession : IDisposable { bool IsDisposed { get; } }
public class Session : ISession
{
    public bool IsDisposed { get; set; }
    public void Dispose() { IsDisposed = true; }
}
public class Repository1 :IRepository
{
    public ISession Session { get; private set; }
    public Repository1(ISession session){ Session = session; }
}
public class Repository2 : IRepository
{
    public ISession Session { get; private set; }
    public Repository2(ISession session){ Session = session; }
}
public class Model1
{
    public IRepository First { get; private set; }
    public IRepository Second { get; private set; }
    public Model1(IRepository first, IRepository second) { First = first; Second = second; }
}
public class Model2
{
    public IRepository Second { get; private set; }
    public Model2(IRepository second) { Second = second; }
}
And here’s the unit test I want to pass:
[Test]
        public void ResolutionsByContext()
        {
            IWindsorContainer root = new WindsorContainer();
            root.Register(Component.For<Model1>().LifeStyle.Transient,
                          Component.For<Model2>().LifeStyle.Transient,
                          Component.For<IRepository>().ImplementedBy<Repository1>().LifeStyle.Transient,
                          Component.For<IRepository>().ImplementedBy<Repository2>().LifeStyle.Transient,
                          Component.For<ISession>().ImplementedBy<Session>().LifeStyle.PerContextScope());

            Model1 model1;
            Model2 model2;
            ISession session1, session2;
            using (var context1 = root.BeginLifetimeScope())
            {
                model1 = context1.Resolve<Model1>();
                session1 = model1.First.Session;
                Assert.AreSame(model1.First.Session, model1.Second.Session);
                Assert.AreSame(context1.Resolve<ISession>(), context1.Resolve<ISession>());

                using (var context2 = root.BeginLifetimeScope())
                {
                    model2 = context2.Resolve<Model2>();
                    session2 = model2.Second.Session;
                    Assert.AreNotSame(model1.First.Session, model2.Second.Session);

                    var anotherModel2 = context2.Resolve<Model2>();
                    Assert.AreSame(anotherModel2.Second.Session, model2.Second.Session);

                    Assert.AreSame(session2, context2.Resolve<ISession>());
                    Assert.AreNotSame(context1.Resolve<ISession>(), context2.Resolve<ISession>());
                }
                Assert.IsTrue(session2.IsDisposed);
                Assert.IsFalse(session1.IsDisposed);
            }
            Assert.IsTrue(session1.IsDisposed);
        }

I copied the name BeginLifetimeScope from Autofac, which inherently supports contextual scopes as a first-class citizen (of which the test passes).  The question now, is how do we get Castle Windsor to do the same?
Initially, I took a look at ISubDependencyResolver and caching variables.  Unfortunately, this didn’t work too well because sub resolvers never got hit if they were resolved from the container directly.
The next step I tried was with lifestyle managers, but alas, the CreationContext was always transient and I was unable to store any state that distinguished between different context resolutions.
After digging deeper into the Windsor codebase and getting into the subsystems and handlers, I found a solution that seems to work.  It passes the test above, but that’s about it.  Test well if you’re gonna use this in production code!!!
Here goes!
First, you have a lifestyle manager to distinguish between other lifestyles.
public class ContextualLifestyleManager : AbstractLifestyleManager
    {
        private object instance;
        public override object Resolve(CreationContext context)
        {
            return instance ?? (instance = base.Resolve(context));
        }
        public override void Dispose()
        {
        }
    }
And finally, the magic happens with this:
public static class ContextualExtensions
    {
        public static ComponentRegistration<T> PerContextScope<T>(this LifestyleGroup<T> group)
        {
            return group.Custom<ContextualLifestyleManager>();
        }
        public static IWindsorContainer BeginLifetimeScope(this IWindsorContainer parent)
        {
            var child = new WindsorContainer();
            var ss = (INamingSubSystem)parent.Kernel.GetSubSystem(SubSystemConstants.NamingKey);
            foreach (var handler in ss.GetHandlers())
            {
                if (handler.ComponentModel.CustomLifestyle == typeof(ContextualLifestyleManager))
                {
                    child.Kernel.AddCustomComponent(handler.ComponentModel);
                }
            }
            parent.AddChildContainer(child);
            return child;
        }
    }
First method is just a helper method to be a little more fluent in the registration for when you want many things to have contextual lifestyle.  The second method is the guts.  Long story short, we create a child container, and duplicate all component models of contextual lifestyle.  Thus, whenever components are resolved, the “override” is found in the child and resolved.  Anything else will be found in the parent.
I was initially pretty happy with this, until I profiled the performance.  With Autofac, creating and disposing 100,000 contexts took 5ms on my computer.  Doing the same with with Windsor took 3.8 seconds.  Out of curiosity, I profiled again, but this time just creating child containers without copying handlers down: 1.9 seconds.  So while this implementation works, it’s not as performant as I’d like it to be….
Maybe I’ll come up with another solution, but for now if the performance is acceptable maybe this would be useful for others!

Wednesday, April 21, 2010

Forcing Castle Windsor to Generate Class Proxies

I don't know why it took me so long to come up with this idea, but to save others potential headaches...have you ever thought "hmmmm, I registered this as an interface with an implementation, but I want Windsor to use a class proxy, not an interface proxy, how do I do that?"

For me, initially I almost went as far as implementing my own ProxyFactory to force it to use class proxy no matter what, and then the light bulb hit me and it turns out that there's a much easier way to accomplish this.

c.Register(Component.For<ConcreteImpl, IService>().Interceptors<AnInterceptor>());

Tada!  The actual service is now a concrete type, so Windsor will go, OK, I need to create a class proxy.  But since it's forwarded to the interface as well, all your dependencies can simply use the interface and everything magically works.

Yay!

Monday, April 5, 2010

Windsor/DynamicProxy/Mixin Powers!

Hmmm, I couldn’t really think of a good title except that this blog post has a little bit of everything of the title.

As with any multithreaded program, deadlocks are a huge pain in the butt, and when they happen it costs time, money, and stress.

In my code base I’ve introduced something called an ExtendedLock, which basically has something like this inside:
   1:  public class ExtendedLock : IExtendedLock {
   2:    public IDisposable Lock() {
   3:      while (!Monitor.TryEnter(this, 5000)) {
   4:        IncrementLockTime();
   5:      }
   6:      return new Disposer(() => Release());
   7:    }
   8:    public event Deadlock;
9: }


Pretty simple.  IncrementLockTime, as the name implies keeps track of how long the current thread has been attempting to acquire the lock.  It returns a Disposer which takes an Action, which releases the lock.  This allows us to take advantage of the using syntax, and avoid boiler plate try/finally (oh, and it avoids typos in Monitor.Exit).  After some configurable amount of time, if the lock cannot be acquired within, say, 2 minutes, it’s probably a good probability your application is blocked somewhere.

Now, using this class basically means replacing lock(_syncRoot) type code with _elock.Lock().  Also, I believe it’s a good candidate for “mixing” into any other component.  Mixins are sort of like multiple-inheritance, but not.  I like to think of mixins as a “can do” rather than “is a.”

Now, we know that C# doesn’t let you do multiple inheritance, but with libraries like Castle’s DynamicProxy2, it lets you do something very similar, and is extremely powerful.  In a sense, it will automatically generate the following code for you:


   1:  public class SomeService : ISomeService, IExtendedLock {
   2:    IExtendedLock _lock = new ExtendedLock();
   3:    public void DoSomething() { }
   4:    IDisposable IExtendedLock.Lock() { return _lock.Lock(); }
   5:  }



_lock is a private instance variable, SomeService implements IExtendedLock, and simply redirects all the interface methods to _lock.  This seems pretty simple and straightforward, but becomes tedious when the type you want to mix in has many methods (as my actual IExtendedLock is).

With Windsor/DynamicProxy, you can do this automatically with minimal amount of code.  For example, first you define something like this:

public interface ILockableDictionary : IDictionary, IExtendedLock { }

Then, you register it in the container:

   1:  var container = new WindsorContainer();
   2:  container.Register(Component.For(typeof(ILockableHashtable))
   3:                                     .LifeStyle.Transient
   4:                                     .Activator<LockableHashtableActivator>());


Now, whenever you need an instance of a lockable hashtable you can simply do something like this:

var hash = container.Resolve<ILockableHashtable>();
using (hash.Lock()) {
hash["1"] = 1;
}


You might be wondering why it’s worth all this trouble, and what’s wrong with regular locks and Monitor.  For our system it’s pretty critical that it stays running 24/7, and every minute it’s down is money lost, so it is in our best interest to detect any problematic condition.

Last but not least, here’s the important code that actually generates the proxy:

   1:  internal class LockableHashtableActivator : DefaultComponentActivator
   2:  {
   3:      public LockableHashtableActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
   4:          : base(model, kernel, onCreation, onDestruction)
   5:      {
   6:      }
   7:   
   8:      public override object Create(CreationContext context)
   9:      {
  10:          IExtendedLock lockMixin = Kernel.Resolve<IExtendedLock>();
  11:   
  12:          // an additional object we want to "mix" with the implementation to provide combined functionality
  13:          ProxyGenerationOptions options = new ProxyGenerationOptions();
  14:          options.AddMixinInstance(lockMixin);
  15:          
  16:          return Kernel.Resolve<ProxyGenerator>().CreateInterfaceProxyWithTarget(
  17:              typeof(IDictionary), // the interface of the implementation
  18:              new[] { typeof(ILockableHashtable) }, // additional interfaces to use
  19:              Activator.CreateInstance<Hashtable>(), // concrete implementation to mix into
  20:              options);
  21:      }
  22:  }


For those who are familiar with Windsor and wondering why I didn’t use the fluent Proxy.Mixins method, it’s because those mixins are created once per registration.  In this case, it is very important that each mixin (which is an extended lock), is transient, otherwise every lockable hashtable ends up with the same extended lock, which is just asking for trouble.

Saturday, August 8, 2009

Dynamic proxies

Life has sure been a roller coaster lately ever since I started working on my new project. I've learned a lot about WCF in the past week. There's really nothing that can teach you faster than trying something out yourself. I've joined the ranks of countless others who have had to deal with implementing service behaviors to handle WCF exceptions (because by default thrown exceptions fault the communication channel), realized that WCF proxy clients breaks the 'using' keyword because someone thought it was a good idea to throw exceptions in Dispose(), and even Unity's InterfaceInterceptor not supporting more than 1 interface! But now that we're talking about proxies, I've been thinking for a while about switching out Unity with a more mature IoC container like Windsor or StructureMap. There are little touches that other containers have that I miss in Unity. For example, auto-wiring. But then again, the integration that Unity has with the rest of the Enterprise Library is very nice, of which I'm using the Logging and Exception Policy blocks, so it made sense in a way that everything in my bin folder just had Microsoft.Practices.*.dll But now I'm seriously reconsidering.
public interface ITestService {
  int Count { get; set; }
  void DoWork();
  bool ShouldDoWork();
}
public class TestService : ITestService {
  public int Count { get; set; }
  public void DoWork() { ++Count; }
  bool ShouldDoWork() { return true; }
}
public void HowDoTheyCompare() {
  var unity = (ITestService)new Microsoft.Practices.Unity.InterceptionExtension.InterfaceInterceptor()
                   .CreateProxy(typeof(ITestService), new TestService());
  var castle = new Castle.DynamicProxy.ProxyGenerator()
                   .CreateInterfaceProxyWithTarget<ITestService>(new TestService());

  Thread.Sleep(1000);

  Stopwatch sw = new Stopwatch();
  sw.Start();
  for (int i = 0; i < 1000000; ++i) { if (unity.ShouldDoWork()) unity.DoWork(); }
  sw.Stop();
  Console.WriteLine("unity: " + sw.ElapsedMilliseconds);
  sw.Reset();
  sw.Start();
  for (int i = 0; i < 1000000; ++i) { if (castle.ShouldDoWork()) castle.DoWork(); }
  sw.Stop();
  Console.WriteLine("castle: " + sw.ElapsedMilliseconds);
}
Results? unity: 1787 castle: 136 From this test it looks like the Unity interception is 13x slower....but wait! I mentioned before that Unity has a bug where it can only proxy one interface....so to resolve that we would need to use the TransparentProxyInterceptor. Let's change it and test again... unity: 30462 castle: 142 Hmmmm....214x slower. I guess we can try the VirtualMethodInterceptor for completeness. After making all methods virtual, here's the results. unity: 3843 castle: 132 Still 29x slower. Whatever DynamicProxy is doing...it's orders of magnitude faster than what Unity's doing.