Structuremap: Singleton class with multiple interfaces

In a recent project, I had the need to implement multiple interfaces in a single Repository class

public class UsageStatisticsRepository : DbContext, IApiKeyCounter, IIpAddresssCounter
{
   
// …
}

We use Structuremap as our IoC container, and attempting to configure the two interfaces as Singletons gave us two instances (naturally), once for each interface.

The solution, was to use the not-so-obvious keyword Forward in order to re-use the Singleton instance for another interface as so:

public class DigitalDiasRegistry : Registry
{
    public DigitalDiasRegistry()
    {
        For<IApiKeyCounter>().Singleton().Use<UsageStatisticsRepository>();
        Forward<IApiKeyCounter, IIpAddressValidator>();
    }
}

 

With that, the problem was solved, and only one instance occured. Since I fiddled some time to figure this out, I thought sharing it would help someone else.

Hett smilefjes