Castle Windsor

Automanual Dependency Injection?

I apologize in advance for using the term 'automanual' but if you've been reading this blog for a while you already know i completely suck at coming up with good names. So bear with me, and you'll probably understand what i mean as you work your way through this post. It really is pretty cool... i promise :p

I'm playing around with some supervising controller MVP stuff using regular ASP.NET webforms. Yes i know, i should be using ASP.NET MVC but i have a strict "i don't touch it before there's a final release"-policy when it comes to Microsoft products (as opposed to my "lemme just build the latest version of the trunk"-policy for various open source products). Anyways, what i'm trying to do is pretty simple. I have a view (ProductList.aspx) which uses a supervising controller (ProductListController). The view (the aspx page) will notify the controller when it needs to do something through events. The controller will then do whatever it needs to do and it will send the data back to the view through properties of the view. If that's not clear to you, read the post i linked to for a much better and detailed explanation.

Since ASP.NET automatically instantiates your aspx page, the easiest thing to do is to let the view create the controller and then pass itself as a parameter to the controller. But the controller also has other dependencies, such as a service which exposes the business logic that we need for this screen. So i have two options: i either create the controller myself and provide all the dependencies, or i use an inversion of control container to create the controller and to wire up all the dependencies. I don't want to have to modify my view code whenever i add/remove a dependency of the controller, so i go with the inversion of control container.

Suppose the constructor of the controller looks like this:

        public ProductListController(IProductList view, IProductsService productsService)

        {

            this.view = view;

            this.productsService = productsService;

        }

Here's where it gets tricky... since the view (which implements the IProductList interface) is asking the container to create a ProductListController, how can the container pass the correct IProductList dependency to the controller? We can't use the regular dependency look-up mechanisms because our controller actually needs the current view instance, but that view instance is asking the container to create the controller! By default, the container has no way whatsoever to resolve the IProductList dependency to the current view instance. So basically, what we want to do in this case is to manually provide the view dependency, but still have the container automatically provide the IProductsService dependency (hence the term 'automanual' which you have to admit is starting to sound pretty good at this point, right?). And of course, we want all of this to work automagically.

It turns out that Castle's Windsor actually does have some slick tricks to make this work. Here's how we can create the controller through the container from the view:

            IProductListController controller =

                Container.Resolve<IProductListController>(new { view = this });

Told you it was slick! It's pretty easy actually... the parameter we pass to the Resolve method is an instance of an anonymous type with a view property. We set the view property to the current aspx instance (using the 'this' keyword obviously) and Windsor is smart enough to figure out that this value should be used to satisfy the view dependency instead of using it's normal look-up mechanisms. The result is that our controller has a reference to the current view, and its IProductsService reference is resolved as the container would typically resolve dependencies. Pretty sweet.

Btw, i googled the term 'automanual' and sure enough, it already exists... but it's not really used in the context of writing code so if this thing sticks, remember where you heard it first ;)

Windsor’s Interceptors and Performance, Part 2

Gael Fraiteur's comment on my previous post made me realize that my performance test in the previous post wasn't all that good...

Let's go back to the part of the code that performed the test:

        [Test]

        public void TestDummyPerformance()

        {

            Time(() => CallMethodXAmountOfTimes(new Dummy(), 1000000));

            Time(() => CallMethodXAmountOfTimes(Container.Resolve<IDummy>(), 1000000));

        }

 

        private void CallMethodXAmountOfTimes(IDummy dummy, int times)

        {

            for (int i = 0; i < times; i++)

            {

                dummy.DoSomething();   

            }

        }

 

        private void Time(Action action)

        {

            DateTime before = DateTime.Now;

            action();

            Console.WriteLine("Time elapsed : " + (DateTime.Now - before));

        }

The Time method has an Action parameter, which basically points to a block of code that will be executed when you call it. In this case the action() line causes the block of code to be executed. I have a habit of trying to write concise code, so the instantiation of the dummy instance is in both cases inlined in the block of code that will be executed by the Time() method. As Gael points out in his comment, Windsor generates a proxy when you request a component that has an interceptor assigned to it, and this is obviously a more expensive operation than simply new-ing a concrete instance. So this extra cost was reflected in the results as well.

If we change the test code to this:

        [Test]

        public void TestDummyPerformance()

        {

            var dummy = new Dummy();

            Time(() => CallMethodXAmountOfTimes(dummy, 1000000));

            var interceptedDummy = Container.Resolve<IDummy>();

            Time(() => CallMethodXAmountOfTimes(interceptedDummy, 1000000));

        }

Now, the difference is not so big as it was in the previous test: Time elapsed : 00:00:00.0100144 Time elapsed : 00:00:00.2403456

Again, this is for one million method calls... in a real world scenario, you probably won't notice the performance hit.

Windsor’s Interceptors and Performance

As i mentioned in a previous post, Windsor's Interceptors are a great way to dynamically add behavior to a class. But what does it cost? There's a lot of stuff going on behind to scenes to make that 'magic' work and surely, there's a performance penalty involved somewhere.

I wanted to see what the cost of this approach is, so i created the following interface and class:

    public interface IDummy

    {

        void DoSomething();

    }

 

    public class Dummy : IDummy

    {

        public void DoSomething() {}

    }

Nothing special there... just a class with a method that doesn't do anything. Combine that with an interceptor that doesn't do anything:

    public class DummyInterceptor : Castle.Core.Interceptor.IInterceptor

    {

        public void Intercept(IInvocation invocation)

        {

            // do nothing, just proceed with the original call

            invocation.Proceed();

        }

    }

And then we configure the component and the interceptor like this:

      <component id="DummyInterceptor" service="Components.DummyInterceptor, Components"

                type="Components.DummyInterceptor, Components"

                lifestyle="transient" />

      <component id="Dummy" service="Components.IDummy, Components" type="Components.Dummy, Components">

 

        <interceptors>

          <interceptor>${DummyInterceptor}</interceptor>

        </interceptors>

 

      </component>

So what do we have now? We have a component which has a method that doesn't do anything. And we've assigned an interceptor that doesn't do anything... it just executes the original call without adding any behavior. Pretty useless, right? Right, but this is ideal to compare the runtime cost of merely intercepting calls to components. So the differences you'll see below are without adding the extra behavior to your components. The differences you'll see below are purely because each call is intercepted.

This is the code i used to test the difference:

        [Test]

        public void TestDummyPerformance()

        {

            Time(() => CallMethodXAmountOfTimes(new Dummy(), 1000000));

            Time(() => CallMethodXAmountOfTimes(Container.Resolve<IDummy>(), 1000000));

        }

 

        private void CallMethodXAmountOfTimes(IDummy dummy, int times)

        {

            for (int i = 0; i < times; i++)

            {

                dummy.DoSomething();   

            }

        }

 

        private void Time(Action action)

        {

            DateTime before = DateTime.Now;

            action();

            Console.WriteLine("Time elapsed : " + (DateTime.Now - before));

        }

First, we call the DoSomething method on a regular Dummy instance 1 million times. The time that takes is written to the Console. Then we call the DoSomething method (again, 1 million times) on an IDummy instance provided by the container, which has our interceptor attached to it (note: when you do not have an interceptor attached, there is NO runtime penalty!).

The output of the test (on my machine) is the following:

Time elapsed : 00:00:00.0100144 Time elapsed : 00:00:00.5808352

As you can see, the second time (using the intercepted instance) is significantly slower than using a concrete instance. But honestly, this is after calling the method one million times. And it only takes about half a second (on a virtualized Windows XP running on a cheap Macbook ;) ) to call this method one million times. In a real-world scenario, you probably won't notice any performance hit unless the code that is intercepted is in a long, tight loop or something like that.

Having said that, i do think using the interceptor approach should be a temporary action in most cases. If you have to debug weird issues, i think adding an extensive logging/tracing interceptor to your components can be extremely valuable without having to pollute your code with logging/tracing statements. But if you want certain behavior to be added to your classes without it being configurable, there certainly are better options to use. PostSharp is a library which enables Aspect Oriented Programming without performance penalties. This approach basically allows you to add specific behavior to methods or classes by placing attributes on them. PostSharp will then modify the compiled byte-code to add the 'aspects' (the behavior that you want to add) to the real code. I'll write a post about this approach soon ;)

Adding behavior without modifying existing code with Windsor

The Windsor container makes it quite easy to add behavior to components, without having to modify their implementation. This could be useful in many scenario's. Suppose you need to log whenever a method from our OrderRepository class is called. But we should be able to turn the logging on and off whenever we want. Preferably, without having to modify the code all the time. Now, you could easily write a logger class that checks for a configuration setting and only logs when needed. This approach would definitely work. But then there's logging code all over the OrderRepository class and in most cases, it's not even necessary since they only want to be able to log under certain circumstances. Should the OrderRepository class really care about the logging? Why litter the code with logging statements?

If you're using the Windsor container, you could easily add logging behavior to the OrderRepository class without having to change any of the existing code. Windsor has this concept of Interceptors. Basically you can assign an interceptor to any component and you can plug in your custom behavior when the component is called. Lets get into an example... Since logging is such a common requirement, we decided to put it in one class instead of littering our entire code base with logging statements. So we wrote the following class:

    public class LoggingInterceptor : Castle.Core.Interceptor.IInterceptor

    {

        private readonly ILogger logger;

 

        public LoggingInterceptor(ILogger logger)

        {

            this.logger = logger;

        }

 

        public void Intercept(IInvocation invocation)

        {

            string methodName =

                invocation.TargetType.FullName + "." + invocation.GetConcreteMethod().Name;

            Log("Entering method: " + methodName);

            invocation.Proceed();

            Log("Leaving mehod: " + methodName);

        }

 

        private void Log(string line)

        {

            logger.WriteLine(DateTime.Now.TimeOfDay + " " + line);

        }

    }

This class implements the IInterceptor interface by implementing the Intercept method. When that method is called we simply construct the full method name, log when we enter the method, call the original method and then we log again when we leave the method. Nothing more, nothing less. Also notice how the LoggingInterceptor has a dependency on an ILogger instance. That instance will be injected by the container as well.

So first of all, we need to define the ILogger and LoggingInterceptor components:

      <component id="ILogger" service="Components.ILogger, Components"

                type="Components.Logger, Components" />

 

      <component id="LoggingInterceptor" service="Components.LoggingInterceptor, Components"

                type="Components.LoggingInterceptor, Components"

                lifestyle="transient" />

Right... so now we need to add this behavior to the OrderRepository class. This only requires modifying the registration of the IOrderRepository component:

      <component id="IOrderRepository"

                service="Components.IOrderRepository, Components"

                type="Components.OrderRepository, Components">

 

        <interceptors>

          <interceptor>${LoggingInterceptor}</interceptor>

        </interceptors>

 

      </component>

What we basically did was tell Windsor that whenever an IOrderRepository is requested, we should return an instance of OrderRepository and each time a method of that instance is called, it needs to be intercepted by our LoggingInterceptor.

So if we simply call the IOrderRepository methods like this (obviously these are dummy calls without real parameters and we're also ignoring return values):

            var repository = Container.Resolve<IOrderRepository>();

 

            repository.GetAll();

            repository.FindOne(new Criteria());

            repository.FindMany(new Criteria());

            repository.GetById(Guid.Empty);

            repository.Store(null);

The following output is logged:

21:53:42.6942016 Entering method: Components.OrderRepository.GetAll
21:53:42.6942016 Leaving mehod: Components.OrderRepository.GetAll
21:53:42.6942016 Entering method: Components.OrderRepository.FindOne
21:53:42.6942016 Leaving mehod: Components.OrderRepository.FindOne
21:53:42.6942016 Entering method: Components.OrderRepository.FindMany
21:53:42.6942016 Leaving mehod: Components.OrderRepository.FindMany
21:53:42.7042160 Entering method: Components.OrderRepository.GetById
21:53:42.7042160 Leaving mehod: Components.OrderRepository.GetById
21:53:42.7042160 Entering method: Components.OrderRepository.Store
21:53:42.7042160 Leaving mehod: Components.OrderRepository.Store

And we didn't have to change the OrderRepository implementation. In fact, we can use our LoggingInterceptor wherever we like, as long as the component to be logged is registered with Windsor. And we can easily switch between logging or no logging by switching config files.

Obviously, this was just a really simple example but i hope you realize how powerful this technique is and how far you can go with this.

Providing configuration data with Windsor

Some classes need configuration data to function properly. This configuration data could be a database connection string, a path, a hostname, a network port, whatever. You typically deal with this by putting the configuration data in your app.config or web.config... either through a Settings file or in the AppSettings or maybe you've created your own configuration section or whatever. And in most cases, when a class needs this data, it simply retrieves it from the Configuration class or the class that was created through your Settings class.

By doing this, you actually create a strong dependency between your class, and the object that provides the configuration data. But you're not really dependent on the object providing the data, since you really only need a bit of data to function. So why not treat the data itself as a dependency?

Let's use our previous example. The OrderDataAccessor class will retrieve Orders from a database. In order to do that, it needs a connection string. Instead of letting the OrderDataAccessor class retrieve that connection string from a config file itself, we'll modify the constructor so that each instance retrieves the connection string when it is created:

        private readonly string _connectionString;

 

        public OrderDataAccessor(string connectionString)

        {

            _connectionString = connectionString;

        }

If the container now needs to create an OrderDataAccessor instance, we get the following exception:

Castle.MicroKernel.Resolvers.DependencyResolverException : Could not resolve non-optional
dependency for 'Components.OrderDataAccessor' (Components.OrderDataAccessor).
Parameter 'connectionString' type 'System.String'

Which makes sense, since we haven't told the container about this 'dependency' yet. Since we're dealing with configuration data now, it's probably better to move our Windsor configuration to a config file as well. First we'll define the castle configuration section in our app.config:

  <configSections>

    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />

  </configSections>

Then we configure our components:

  <castle>

    <components>

      <component id="IOrderDataAccessor"

          service="Components.IOrderDataAccessor, Components"

          type="Components.OrderDataAccessor, Components">

 

        <parameters>

          <connectionString>myConnectionString</connectionString>

        </parameters>

 

      </component>

 

      <component id="IOrderRepository"

                service="Components.IOrderRepository, Components"

                type="Components.OrderRepository, Components" />

 

    </components>

 

  </castle>

And that's it... Whenever the container instantiates an OrderDataAccessor instance, it will pass 'myConnectionString' to the connectionString parameter.

There's one issue with this though... In a real system, you'd have more than one DataAccessor class, and having to specify the connectionString for each one of them would be a prime example of suckage. So let's modify our config file a little bit:

  <castle>

 

    <properties>

      <connectionString>myConnectionString</connectionString>

    </properties>

 

    <components>

      <component id="IOrderDataAccessor"

          service="Components.IOrderDataAccessor, Components"

          type="Components.OrderDataAccessor, Components">

 

        <parameters>

          <connectionString>#{connectionString}</connectionString>

        </parameters>

 

      </component>

 

      <component id="IOrderRepository"

                service="Components.IOrderRepository, Components"

                type="Components.OrderRepository, Components" />

 

    </components>

 

  </castle>

That's better... Now we can just refer to the connectionString whenever we need it so we'd only have to modify it in one place.

Keep in mind that if you put the Windsor configuration in your app.config/web.config file, you need to instantiate the container like this:

            _container = new WindsorContainer(new XmlInterpreter());

So as you can see, you can also use the IoC container to keep dependencies on configuration-providing-classes completely out of your code by 'promoting' the required configuration data to actual dependencies of your components.