开发者

C# ASP.NET Thread Safe static read only field

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开发者_如何学Go create and return instance...
    }
}

Is IoC.Container going to be thread safe?


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.


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]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜