Showing posts with label Castle. Show all posts
Showing posts with label Castle. Show all posts

There are a number of inversion of control containers out there so I thought it would be an interesting experiment to do a simple benchmark. There are different ways that one can instantiate a type in .NET, for example via the new operator, Activator, GetUninitializedObject and Dynamic Method. The performance difference between these methods are in some cases quite high, maybe the same is true for these IoC containers? Granted IoC containers do more than just create objects so other factors will probably play a big role in the results.

So here are the contestants:

I have been using Castle Windsor since 2005 and I think it is the best of the bunch, so I guess I am unconsciously biased toward Windsor.  However I will try to make this benchmark as objective as I can.

The scenario for this test:

  • Have each IoC container resolve a UserController 1000 000 times
  • The UserController will have two constructor dependencies
  • Run the test with transient (new instance for each resolve) and singleton components

The UserController looks like this:

public class UserController
{
    private IUserRepository repository;
    private IAuthentificationService authService;

    public UserController(IUserRepository repository, IAuthentificationService authService)
    {
        this.repository = repository;
        this.authService = authService;
    }
}

I have also a general container interface that the benchmark engine will use. Each container will implement this interface.

public interface IContainer
{
    string Name { get; }

    T Resolve<T>();
    
    void SetupForTransientTest();
    void SetupForSingletonTest();
}

All tests used the latest released version of each library. Before you interpret these charts please observe that the measurement is for one million component resolves which means the actual time difference between each container is actually very small.

Here are the results when all components were setup as singletons:

IoCSingleton

Here are the results when all components were setup as transient:

IoCTransient

So what does these charts tell us? Lets take the biggest difference in the transient case, Spring.NET took 44.149 seconds and Unity took 8.164 seconds, what is the actual difference when resolving a single instance?

  Spring.NET : 44.149 / 1000000 = 0.000044149 seconds
  Unity      :  8.164 / 1000000 = 0.000008164 seconds

So the actual difference is only about 36 microseconds. Another way to put these values into perspective is to compare against the new operator. I created a NewOperatorContainer with a resolve method that looks like this:

public T Resolve<T>()
{
    object o = new UserController(new LdapUserRepository(), new DefaultAuthentificationService());
    return (T) o;
}

OK, comparing the above with an inversion of control container is like comparing apples to oranges, an IoC handles so much more than just object creation. Also an IoC cannot use the new operator directly but must use one of the other methods. My guess is that all IoC containers in this test uses an approach which involve IL Generation which if cashed comes close to using the new operator directly. Anyway I think it will show just how small the difference between the real IoC containers are. In order to visualize this I needed to invert the values so that high means fast and low means slow.

IoCInversed

Update: The above chart can be very misleading. The x-axis is not seconds but 1/s. I hope it shows that the difference between the containers are very small compared to instantiating the objects manually.

OK, can we draw any conclusion from the test? Well I think we can say that performance should not be an issue when choosing one of these IoC containers. The difference is too small. When you choose which container to use you should consider other aspects, like how invasive the container is to they way you want to work.

For the complete code: IoCBenchmark.zip

The new statistics class in Hibernate 2.0 is a great tool to use for monitoring potential performance problems with your app. The class exposes a large number of counters and measurements. Here are some highlights of what is available:

  • EntityDeleteCount
  • EntityInsertCount
  • EntityLoadCount
  • EntityUpdateCount
  • QueryExecutionCount
  • QueryExecutionMaxTime
  • QueryExecutionMaxTimeQueryString
  • QueryCacheHitCount
  • ConnectCount
  • SessionCloseCount
  • SessionOpenCount
  • CollectionLoadCount
  • CollectionUpdateCount
  • CollectionRemoveCount
  • Queries
  • PrepareStatementCount

The statistics engine can be turned on/off dynamically with the IsStatisticsEnabled property and you can get statistics on specific entities as well.

Just to try this out I created a MonoRail filter that checks for "nhibstats" in the query parameters of the request. If the parameter is found it will turn on the nhibernate statistics, this is done before the controller action is executed. After the action as completed it will add the stats data to the PropertyBag so the view can access it.

public class NHibernateStatsFilter : IFilter
{
    public bool Perform(ExecuteWhen exec, IEngineContext context, IController controller,
                        IControllerContext controllerContext)
    {
        if (context.Request["nhibstats"] == null)
            return; 
        
        if (exec == ExecuteWhen.BeforeAction)
        {
            sessionFactory.Statistics.Clear();
            sessionFactory.Statistics.IsStatisticsEnabled = true;
        }
        else if (exec == ExecuteWhen.AfterAction)
        {
            controllerContext.PropertyBag["nhibernate_stats"] = sessionFactory.Statistics;
            sessionFactory.Statistics.IsStatisticsEnabled = false;
        }
    }
}

I use the same filter for both the before and after action "events", this means that you have to specify the filter attribute like this:
[Filter(ExecuteWhen.BeforeAction | ExecuteWhen.AfterAction, typeof(NHibernateStatsFilter))]
public class BaseController : Controller
{
        
}
Now you can add to your top layout view something like this:
<?brail if IsDefined("nhibernate_stats"): ?>
    <dl>
        <dt>EntityInsertCount</dt>
        <dd>${nhibernate_stats.EntityInsertCount}</dd>        
        <dt>EntityUpdateCount</dt>
        <dd>${nhibernate_stats.EntityUpdateCount}</dd>        
        .
        ..
        ...
    </dl>
<?brail end ?>

I think this could be really useful. Now you don't have to open SQL Profiler whenever you want to know what NHibernate is up to!

For a previous project I extended the IoC container Castle Windsor to support dynamic component selection. In this case it was extended to select the correct implementation based on the current user type. I even wrote a CodeProject article about it, but for some reason I never published the article. Well this morning I did submit it and it can be found here. I will try to outline the changes I did in this post as well.

Why do you need dynamic component selection? Well imagine you are going to develop a web application that is used by B2C (Consumer), B2P (Partner) and B2E (Employee) users. The B2C users has their profile and password in a local database, the B2P users profile can only be accessed via an external third party web service and the B2E users are in an LDAP server.

In this kind of scenario you would do an interface for a user repository and then an implementation for each user type. If this web application serves all these user types from a single instance then you need a factory to return the correct implementation based on the current user type. If you have many different scenarios where the implementation will be different based on some common runtime condition then it would be nice to declare that (for example in a xml configuration file) and then have the inversion of control container dynamically select the correct component. This way you would not need to create a bunch of almost identical factories for each scenario.

So what we want to do is basically state in the windsor configuration which implementation coresponds to which user type.

<components>
    <component	id="b2e.user.repository"
		service="ExtendingWindsor.IUserRepository, ExtendingWindsor"
		type="ExtendingWindsor.EmployeeUserRepository, ExtendingWindsor" 
		channel="B2E" />
    
    <component	id="b2c.user.repository"
		service="ExtendingWindsor.IUserRepository, ExtendingWindsor"
		type="ExtendingWindsor.ConsumerUserRepository, ExtendingWindsor" 
		channel="B2C" />

    <component	id="b2p.user.repository"
		service="ExtendingWindsor.IUserRepository, ExtendingWindsor"
		type="ExtendingWindsor.PartnerUserRepository, ExtendingWindsor" 
		channel="B2P" />
</components>

The channel attribute in the above xml is not something that exists in the standard Castle Windsor configuration schema. However Castle Windsor allows for additional attributes so the only thing we need to do now is to extend the container so that when it searches for a implementation of the IUserRepository interface it will take the correct one.

One way to acheive this is to exchange the default naming subsystem with one that inherits from DefaultNamingSubSystem and change the behavior of the GetHandler method.

public class ExtendedNamingSubSystem : DefaultNamingSubSystem
{
    public override IHandler GetHandler(Type service)
    {
        IHandler[] handlers = base.GetHandlers(service);

        if (handlers.Length < 2)
            return base.GetHandler(service);

        UserPrincipal user = (UserPrincipal) Thread.CurrentPrincipal;

        foreach (IHandler handler in handlers)
        {
            string channel = handler.ComponentModel.Configuration.Attributes["channel"];
            if (channel == user.Channel)
            {
                return handler;
            }
        }

        // use default
        return base.GetHandler(service);
    }
}

What we need to do now is to replace the default NamingSubSystem with our own. To exchange the NamingSubSystem of the underlying kernel in Castle Windsor is a little more problematic than it should. We need to use the constructur that takes in an implementation of IKernel.

This is what we have to do:

IKernel kernel = new DefaultKernel();
kernel.AddSubSystem(SubSystemConstants.NamingKey, new ExtendedNamingSubSystem());
XmlInterpreter interpreter = new XmlInterpreter();
DefaultComponentInstaller installer = new DefaultComponentInstaller();

interpreter.Kernel = kernel;
interpreter.ProcessResource(interpreter.Source, kernel.ConfigurationStore);

WindsorContainer container = new WindsorContainer(kernel, installer);
container.Installer.SetUp(container, kernel.ConfigurationStore);

This is setup is a little more complex than what you normaly do:

WindsorContainer container = new WindsorContainer(new XmlInterpreter())

But there is no constructor that takes an IKernel and a IConfigurationInterpreter. I have thought about submitting such a constructor as a patch to the castle team but have not gotten around to it. Anyway now that we are done we can do this:

IUserRepository repos = container.Resolve<IUserRepository>();

The container will dynamically select the correct component based on the current principal. This also works if you have a component that has a constructor dependency to the IUserRepository. You have think about the lifestyle though so that you do not store a reference to a IUserRepository implementation in a singleton component.

Please observe that the above implementation of ExtendedNamingSubSystem is just a proof of concept implementation. For a real implementation you should try to reduce the need to call base.GetHandlers(service).

Update: Instead of extending the DefaultNamingSubSystem yourself you can use the KeySearchNamingSubsystem which is included in the Castle Windsor release. This allows you to use meta data inserted in the component id to do dynamic component selection. 

I really like the new component registration API in Castle Windsor, if you compile the trunk yourself with Visual Studio 2008 you also get some .NET 3.5 only methods that uses lambda functions. These new functions make the API really powerfull.

// Register services
Container.Register(AllTypes.Pick()
.FromAssembly(Assembly.GetExecutingAssembly())
.If(type => type.Namespace == typeof(ISearchService).Namespace)
.WithService.FirstInterface());

This registers all classes that exists in the same namespace as the ISearchService interface. When windsor registers the classes it will take the first interface as the main interface (the one you can use to get the component). The nice this is that this can be used together with the xml based configuration since only components that are not already registered will be added. This gives you a change to later change a component via the xml configuration.

Ayende has been posting a lot about automatic component registration using Binsor windsor configuration scripts. The programming experience when all components are registered and hooked up automatically is really nice. It lets you focus on the important stuff.

I have been working on a WPF application lately and today I came across a rather common scenario where I needed to do stuff in a background thread (in order to not lock the UI). In this scenario I needed to do indexing, during the indexing I want the UI to be updated with progress (what file is being index, how many has been indexed, etc). I handled this by having the indexing service expose some progress events that the UI could subscribe to, like this:

private void OnStartIndexing()
{
    var indexer = new FileIndexer();
    indexer.IndexingFile += IndexingFileCallback;
    indexer.IndexingCompleted += IndexingCompletedCallback;
    indexer.SavingIndexStarted += IndexerSavingIndexStarted;

    ThreadPool.QueueUserWorkItem(x => { indexer.Run(); });
}

protected void IndexingCompletedCallback()
{
    View.HideInfoText();
}

The problem here is that the function IndexingCompletedCallback is not being called in the UI thread and will throw an exception. To solve this you have to use the Dispatcher like this:

Action action = delegate()
{
    Views.HideInfo();
};
Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);

When I saw this I thought that this could be handled in a more general declarative way by using function attributes and AOP. So I tried to get this to work:

[UseDispatcher]
protected virtual void IndexingCompletedCallback()
{
    View.HideInfoText();
}

The fun part was that it was very easy to do, since I already used Castle Windsor for my presenters it was just a matter of configuring my base presenter class with an interceptor and in the interceptor it was just a matter of calling the invocation.Proceed() in a delegate passed to the Dispatcher.

Just for completeness here is the code for the base presenter:
[Interceptor(typeof(PresenterInterceptor))]
public abstract class Presenter<T>
{
    public T View { get; private set; }
    
    public void Wireup(T view)
    {
        View = view;
        Initialize();
    }

    protected abstract void Initialize();
}
And here is the interceptor:
public class PresenterInterceptor : IInterceptor
{
    private IDispatcher dispatcher;

    public PresenterInterceptor(IDispatcher dispatcher)
    {
        this.dispatcher = dispatcher;
    }

    public void Intercept(IInvocation invocation)
    {
        object[] attributes = invocation.Method.GetCustomAttributes(typeof (UseDispatcherAttribute), true);
        
        if (attributes.Length == 0)
        {
            invocation.Proceed();
            return;
        }

        dispatcher.RunInUI(invocation.Proceed);
    }
}

Okey so after all that I now discovered that the BackgroundWorker might have been a good choise for this scenario since it has progress event that seems to automatically be executed in the UI thread, I am not sure yet. I will have to try it and do another blog post about it. But I still feel that this solution is nice and easy, and if you use Castle Windsor it is a quick thing to implement.

Ok, maybe a little to much code for a first blogpost, but I named the blog slickcode so why not :)