您如何以静态方法在dotnet核心项目中注入IConfiguration对象?

问题描述

我有一个与this one类似的Redis商店。我的问题是,由于我使用的是.Net Core,因此在第15行上,我应该使用通常注入到构造函数中的配置对象。

但是,不能在静态构造函数中注入配置对象,因为静态构造函数在C#中应该是无参数的。

我尝试添加一个静态方法来初始化config对象,但是构造函数抛出NullReferenceException,因为显然ctor仍然是在Init方法之前首先被调用的,并且它需要config对象。要做?

似乎不是一个好的解决方法。

解决方法

我建议您不要改用较新的模式并正确使用DI,而不是使用静态方法并尝试使其正常工作(提示:它永远不能与静态构造函数一起使用)。

如果您真的不需要惰性,这就像注入IConnectionMultiplexer一样简单:

services.AddScoped<IConnectionMultiplexer>(s => ConnectionMultiplexer.Connect(configuration["someSettings"]));

如果您确实需要懒惰:

// public interface IRedisStore { IConnectionMultiplexer RedisConnection { get; } } 
public class RedisStore : IRedisStore
{
    private readonly Lazy<ConnectionMultiplexer> LazyConnection;

    public RedisStore(IConfiguration configuration)
    {
        var configurationOptions = new ConfigurationOptions
        {
            EndPoints = { configuration["someSettings"] }
        };

        LazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configurationOptions));
    }

    public IConnectionMultiplexer RedisConnection => LazyConnection.Value;        
}

,然后将其注入:

services.AddScoped<IRedisStore,RedisStore>());

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...