Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register generic interfaces in StructureMap

How do I register all the instances of a generic interface in Structured Map?

I know how to do this for a none generic interface:

internal class MVCDemoRegistry : Registry
    {
        public MVCDemoRegistry()
        {
            Scan(x =>
            {
                x.Assembly("MVCDemo");
                x.Assembly("MVCDemo.Infrastructure");
                x.Assembly("MVCDemo.Services");

                x.AddAllTypesOf<ISupplyView>();
            });
        }
    }
like image 409
AwkwardCoder Avatar asked Jul 17 '09 15:07

AwkwardCoder


1 Answers

I would go with something like

// in IToaster.cs
public interface IToaster<T> {}

// in your StructureMap registry
Scan(x =>
{
    x.Assembly("MVCDemo");
    x.Assembly("MVCDemo.Infrastructure");
    x.Assembly("MVCDemo.Services");

    x.AddAllTypesOf(typeof(IToaster<>))
});

The key here is that this approach uses the non-generic overload of AddAllTypesOf(). Otherwise this becomes a sticky widget indeed.

See this SO thread for a good discussion around these concerns: StructureMap Auto registration for generic types using Scan

This should do the trick unless there's something about your approach I'm missing - feel free to update if so.

like image 186
sparker Avatar answered Oct 16 '22 10:10

sparker