Search code examples
c#interfacestructuremapinstances

Using StructureMap with derived interfaces


I have an object hierarchy similar to the following:

interface IVideoStream { }

abstract class VideoStream : IVideoStream { }

interface IVideoStreamTypeA : IVideoStream { /* Specific for type A */ }

interface IVideoStreamTypeB : IVideoStream { /* Specific for type B */ }

class VideoStreamTypeA : IVideoStreamTypeA { }

class VideoStreamTypeB : IVideoStreamTypeB { }

There should be a single instance of both VideoStreamTypeA and VideoStreamTypeB, as they wrap some resources. Some classes consume IVideoStreamTypeA or IVideoStreamTypeB directly, and some classes take a list of IVideoStream.

The register code looks like this:

class MyRegistry: Registry
{
    public MyRegistry()
    {
        For<IVideoStreamTypeA>().Use<VideoStreamTypeA>()
            .Ctor<>() // Specific initialization
        For<IVideoStreamTypeB>().Use<VideoStreamTypeB>()
            .Ctor<>() // Specific initialization

        For<IVideoStreamTypeA>().Singleton();
        For<IVideoStreamTypeB>().Singleton();
    }
}

Finally, there are some classes that take a list of IVideoStream:

class MyClass 
{
    public MyClass(IEnumerable<IVideoStream> streams) { }
}

With the current registry code, the "streams" parameter is empty. How do I get StructureMap to inject the two instances from above?


Solution

  • My current approach is to use the following:

    Forward<IVideoStreamTypeA, IVideoStream>();
    Forward<IVideoStreamTypeB, IVideoStream>();
    

    But I'm not sure it's the best solution