如何在dotnet核心项目的静态方法中注入一个IConfiguration对象



我有一个类似于此的Redis存储。我的问题是,因为我正在使用。Net Core,在第15行,我应该使用我通常在构造函数中注入的配置对象。

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

我尝试添加一个静态方法来初始化配置对象,但随后构造函数抛出NullReferenceException,因为很明显,ctor仍然是在Init方法之前首先调用的,它需要配置对象。。。那么该怎么办呢?

这似乎不是一个好的变通办法。

与其用statics做所有的工作并试图让它工作(提示:它永远不会用静态构造函数工作(,我建议您转移到更新的模式并正确使用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>());

最新更新