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()
        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

About digitaldias

Software Engineer during the day, photographer, videographer and gamer in the evening. Also a father of 3. Pedro has a strong passion for technology, and gladly shares his findings with enthusiasm.

View all posts by digitaldias →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.