开发者

C# ASP.NET Thread Safe static read only field

开发者 https://www.devze.com 2022-12-21 22:22 出处:网络
I have the following code in my ASP.NET project public sealed class IoC { private static readonly IDependencyResolver resolver =

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

精彩评论

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

关注公众号