Sami
Sami

Reputation: 413

How do you inject in dotnet core project in static method an IConfiguration object?

I have a Redis store similar to this one. My problem is, since I am using .Net Core, on line 15, I should use configuration object that I normally inject in the constructor.

However, one cannot inject the configuration object in the static constructor, as static constructor should be parameterless in C#.

I tried adding a static method to initialise the config object, but then the constructor throws NullReferenceException because obviously the ctor is still called first, before the Init method, and it needs the config object... so what to do?

Doesn't seem like a good workaround.

Upvotes: 2

Views: 698

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

Instead of doing all that work with statics and trying to get it to work (hint: it'd never work with a static constructor), I'd suggest you to move to newer patterns and use DI correctly.

If you don't really need the lazyness, this is as simple as injecting IConnectionMultiplexer:

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

If you do need the lazyness:

// 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;        
}

and you'd inject it with:

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

Upvotes: 1

Related Questions