Registering types with a Per Thread lifetime

The following code snippet defines an extension method that allows registration of instances with a lifetime equal to the lifetime of a single thread. This allows the use of types that are not thread-safe.

using System;

using SimpleInjector;

public static class PerThreadRegistrationsExtensions
{
    public static void RegisterPerThread<TService, TImplementation>(
        this Container container) 
        where TService : class
        where TImplementation : class, TService
    {
        Func<TService> instanceCreator = 
            () => container.GetInstance<TImplementation>();

        RegisterPerThread<TService>(container, instanceCreator);
    }

    public static void RegisterPerThread<TService>(this Container container,
        Func<TService> instanceCreator) where TService : class
    {
        var creator = new PerThreadInstanceCreator<TService>(instanceCreator);
        container.Register<TService>(creator.GetInstance);
    }

    private sealed class PerThreadInstanceCreator<T> where T : class
    {
        [ThreadStatic]
        private static T instance;

        private Func<T> instanceCreator;

        internal PerThreadInstanceCreator(Func<T> instanceCreator)
        {
            this.instanceCreator = instanceCreator;
        }

        internal T GetInstance()
        {
            if (instance == null)
            {
                instance = this.instanceCreator();
            }

            return instance;
        }
    }
}

Last edited Apr 26, 2011 at 5:40 PM by dot_NET_Junkie, version 1