IServiceCollection.AddSingleton 线程安全吗?

问题描述 投票:0回答:1

考虑以下扩展功能:

public static class Extensions
{
    public static IServiceCollection AttachNativeLogger(this IServiceCollection services, ILogger logger)
    {
        // internal mechanism to forward native logging to ILogger interface:
        ArgumentNullException.ThrowIfNull(services);
        var curLevel = Enum.GetValues(typeof(LogLevel)).Cast<LogLevel>().FirstOrDefault(logger.IsEnabled);
        var implementationInstance = new NativeLoggerForwarder(logger);
        implementationInstance.SetLogLevel(curLevel);
        // not thread safe ?
        services.AddSingleton(typeof(NativeLoggerForwarder), implementationInstance);

        return services;
    }
}

在上面的代码中,我应该将:

services.AddSingleton(typeof(NativeLoggerForwarder), implementationInstance)
放在
lock(object)
中吗?

由于这是一个静态类,我无法理解如何才能做到这一点,因为我无法定义外部:

public class A {
    private static Object object = new Object();
    private static void foo() {
        lock(object) {
            // thread-safe
        }
    }
}

文档没有提到任何与线程安全相关的问题:

c# thread-safety singleton
1个回答
0
投票

通过查看:

我想说它不是线程安全的,无需质疑为什么要从多个线程设置容器。我没有遇到任何使用的锁或并发集合。

在上面的代码中,我应该将: services.AddSingleton(typeof(NativeLoggerForwarder),implementationInstance) 包含在锁(对象)内吗?

此外,您还必须检查该服务是否已注册。

© www.soinside.com 2019 - 2024. All rights reserved.