Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Contextual Binding with StructureMap 2.5

What is Contextual Binding?
Contextual Binding is the ability to switch out different concrete implementations of a service (i.e. class) at runtime depending on the context in which they are used.

One really cool thing about StructureMap is that it is very flexible.  Most times there are multiple ways to accomplish the same goal.  The reason for this is because everyone's needs are different and the tool takes this into account.

There are 2 (at least 2, maybe more :) ) ways that we can perform contextual binding with StructureMap.

Context Setup - The classes we will be using
We will be creating a 'consumer' who likes to consumer soda.  The type of soda that the consumer will drink will be injected at runtime via StructureMap and we will swap the soda out at runtime with contextual binding

Consumer Class - The class that consumes Soda

    public class Consumer
    {
        public Consumer(ISoda soda)
        {
            Soda = soda;
        }

        public string WhatTypeOfSodaAreYouDrinking()
        {
            return Soda.Name;
        }

        public Int32 HowManyCaloriesDoYouHave()
        {
            return Soda.Calories;
        }

        public ISoda Soda { get; set; }
    }

ISoda Interface - The contract for our soda objects

    public interface ISoda
    {
        string Name { get;}
        Int32 Calories { get; }
    }

DrPepper Class - An implementation of ISoda

    public class DrPepper : ISoda {
        public string Name { get { return "DrPepper"; } }
        public int Calories { get { return 250; } }
    }

DietCoke Class - An implementation of ISoda

    public class DietCoke : ISoda
    {
        public string Name { get { return "Diet Coke"; } }
        public Int32 Calories { get { return 99; } }
    }

Setting up StructureMap to know about the various classes

StructureMapConfiguration.ForRequestedType<consumer>().AddConcreteType<consumer>();
StructureMapConfiguration.AddInstanceOf<ISoda>().UsingConcreteType<DrPepper>().WithName( "DrPepper" );
StructureMapConfiguration.AddInstanceOf<ISoda>().UsingConcreteType<DietCoke>().WithName("DietCoke");

Setting the Default Instance on the fly:

If you only need/want to swap out a single class at runtime the simplest way may be to just change the instance on the fly. 

The code below will show how to do that.

ObjectFactory.SetDefaultInstanceName<ISoda>( "DietCoke" );
var consumer = ObjectFactory.GetInstance<Consumer>();

// we now should have a consumer with an instance of DietCoke

Using Profiles:

A profile in StructureMap is basically a configuration group that allows you to prewire which types you would like to use for various contracts ahead of time.  By using a contract you can swap out many concrete types with a single line of code.

The code below will show how to setup a profile as well as how to use that profile.

Creating the profiles

ProfileExpression drPepperProfile = StructureMapConfiguration.CreateProfile( "DrPepper" );
drPepperProfile.For<ISoda>().UseConcreteType<DrPepper>();

ProfileExpression dietCokeProfile = StructureMapConfiguration.CreateProfile("DietCoke");
dietCokeProfile.For<ISoda>().UseConcreteType<DietCoke>();

Setting the profiles

ObjectFactory.Profile = "DrPepper";
var consumer = ObjectFactory.GetInstance<Consumer>();

// we now should have a consumer with an instance of DrPepper

As you can see, setting up Contextual Binding in StructureMap is pretty easy and is a very powerful tool. 

Till next time,

[----- Remember to check out DimeCasts.Net -----]


Posted 08-13-2008 7:13 AM by Derik Whittaker

[Advertisement]

Comments

DotNetKicks.com wrote Contextual Binding with StructureMap 2.5
on 08-13-2008 8:17 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Jimmy Bogard wrote re: Contextual Binding with StructureMap 2.5
on 08-13-2008 8:33 AM

It also looks like the n-deep "With" method will make it in to SM 2.5.  This allows you to do provide an instance for a single call to GetInstance, in a thread-safe manner.

For instance, I was using instance names and profiles in a WCF scenario, but since it was two lines, the default instance could get set, a thread switch happened, and now the wrong instance got set for something else.

Ray Akkanson wrote re: Contextual Binding with StructureMap 2.5
on 08-13-2008 9:11 AM

Greate Article.

Ray Akkanson

Dew Drop - August 13, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - August 13, 2008 | Alvin Ashcraft's Morning Dew
on 08-13-2008 9:31 AM

Pingback from  Dew Drop - August 13, 2008 | Alvin Ashcraft's Morning Dew

Arjan`s World » LINKBLOG for August 14, 2008 wrote Arjan`s World &raquo; LINKBLOG for August 14, 2008
on 08-14-2008 3:03 PM

Pingback from  Arjan`s World    &raquo; LINKBLOG for August 14, 2008

Erik wrote re: Contextual Binding with StructureMap 2.5
on 08-21-2008 2:54 PM

That's neat - thanks for the writeup. =)

Ed C. wrote re: Contextual Binding with StructureMap 2.5
on 09-08-2008 6:51 PM

Hi,

This is great! Is this possible to do declaratively in the XML config file? Or only in the fluent interface?

Thanks!

Ed C.

Derik Whittaker wrote re: Contextual Binding with StructureMap 2.5
on 09-08-2008 7:48 PM

@Ed,

I have not tried.  I will take a look and let u know.

Jeremy D. Miller -- The Shade Tree Developer wrote A Gentle Quickstart for StructureMap 2.5
on 11-30-2008 10:56 PM

The most general question I get with StructureMap is “how do I get started?” Personally, I’d recommend

Community Blogs wrote A Gentle Quickstart for StructureMap 2.5
on 11-30-2008 11:48 PM

The most general question I get with StructureMap is “how do I get started?” Personally, I’d recommend

A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas wrote A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas
on 12-02-2008 10:16 AM

Pingback from  A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas

A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas wrote A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas
on 12-03-2008 11:04 AM

Pingback from  A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas

A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas wrote A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas
on 12-04-2008 11:09 AM

Pingback from  A Gentle Quickstart for StructureMap 2.5 - taccato! trend tracker, cool hunting, new business ideas

Shazia wrote re: Contextual Binding with StructureMap 2.5
on 12-17-2008 7:45 AM

This article have useful and important information.  These information is very reasonable.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)