Using named instances as constructor arguments

I’ve previously discussed the usefulness of StructureMap’s named instances, as well as bemoaning how fugly the syntax is for using them:

For<IUserRepository>()
    .Ctor<ISession>("session").Use(c => c.GetInstance<ISession>("UserDB"));

I submitted a pull request to improve it, but the other day I realised I could fix it in the current version with an extension method:

public static class StructureMapExtensions
{
    public static SmartInstance<T> Named<T, CTORTYPE>(this SmartInstance<T>.DependencyExpression<CTORTYPE> instance, string name)
    {
        return instance.Is(c => c.GetInstance<CTORTYPE>(name));
    }
}

Which means you can say:

For<IUserRepository>()
    .Ctor<ISession>("session").Named("UserDB");

Yay!

Advertisements

One thought on “Using named instances as constructor arguments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s