1
votes

I am trying to use structure map to get an instance of StackExchangeRedisCacheClient https://github.com/imperugo/StackExchange.Redis.Extensions/blob/master/src/StackExchange.Redis.Extensions.Core/StackExchangeRedisCacheClient.cs

I have seen other questions that ask about specifying a parameterless constructor instead of a constructor with parameters. However, I want to specify a specific constructor that has parameters.

I can't find any examples of this.

I want to use this constructor:

public StackExchangeRedisCacheClient(ISerializer serializer, IRedisCachingConfiguration configuration = null)

I want StructureMap to get an instance of ISerializer and give a null for IRedisCachingConfiguration. How can I do this?

I want to do something similar to this but it doesn't work:

For<ISerializer>().Singleton().Use<JilSerializer>().SelectConstructor(() => new JilSerializer());
For<ICacheClient>().Singleton().Use<StackExchangeRedisCacheClient>().SelectConstructor(() => new StackExchangeRedisCacheClient(GetInstance<ISerializer>, null));
1

1 Answers

1
votes

It should work if you configure the container with a factory function that returns a null instance of the IRedisCachingConfiguration. The actual instances do not need to be resolved in the SelectConstructor expression, as this is just used for matching the constructor, hence the nulls.

For<ISerializer>().Singleton().Use<JilSerializer>();
For<IRedisCachingConfiguration>().Singleton()
    .Use("null config", () => (IRedisCachingConfiguration)null);
For<ICacheClient>().Singleton()
    .Use<StackExchangeRedisCacheClient>()
    .SelectConstructor(() => new StackExchangeRedisCacheClient(
        (ISerializer)null,
        (IRedisCachingConfiguration)null));

Or another approach would be to configure a factory function for your ICacheClient and simply invoke the constructor you want, bypassing the need to configure a null IRedisCachingConfiguration.

For<ICacheClient>().Singleton().Use(c => 
    new StackExchangeRedisCacheClient(c.GetInstance<ISerializer>(), null));