views:

182

answers:

2

I have the following code in my ASP.NET project

public sealed class IoC
{
    private static readonly IDependencyResolver resolver =
        Service.Get("IDependencyResolver") as IDependencyResolver;

    static IoC()
    {
    }

    private IoC()
    {
    }

    public static IDependencyResolver Container
    {
         get
         {
             return resolver;
         }
    }
}

public static class Service
{
    public static object Get(string serviceName)
    {
        // Code to create and return instance...
    }
}

Is IoC.Container going to be thread safe?

A: 

IoC itself looks ok, but the whole structure will not be thread-safe if resolver is not thread safe. If you want to have resolver per thread you can use attribute [ThreadStatic]

Andrey
I want all threads to use the same instance of resolver implementation
Emilian
A: 

Initialization of static fields is thread-safe: that is, the .NET runtime guarantees that your field will be initialized only once in the program, no matter how many threads access it and in what order.

As Andrey points out, the Service.Get method itself needs to be thread-safe.

Tim Robinson
From my understanding Service.Get will be called once per application domain so every thread will receive the same resolver instance is this correct?
Emilian
Your `private static readonly IDependencyResolver resolver` field will be initialized only once per app domain, correct. It's still possible to do something unsafe inside `Get`, but I guess that's not what you're asking.
Tim Robinson
In Service.Get I'm only reading resolver type from web.config and use Activator to get an resolver instance of that type. But my concern was that every thread that process my requests use the same resolver instance.
Emilian
Yep, that's safe. Btw, don't you want `(IDependencyResolver) Service.Get("IDependencyResolver")` instead? I'd rather have an `InvalidCastException` if things go wrong - the `as` keyword just leaves you with a null reference.
Tim Robinson
You're right! Thanks for that one.
Emilian