Jonathan Birkholz

Structure Map 2.6 Constructing the Concrete Type

Basic Use with Func

Ryan yet again was asking for how to do another crazy thing with Structure Map. :)

He wanted to know if there was a way to control the construction of a concrete type. Well.. he didn’t put it that way but it is what he wanted to know.

Besides the regular For().Use()… we have the ability to construct the concrete type ourselves with a simple action.

To demo this I have a Foo class that accepts a string in the constructor.

1
2
3
4
5
6
7
8
9
class Foo : IFoo
{
public Foo(string message)
{
Message = message;
}
public string Message { get; set; }
}

We want to pass in the message explicitly so we configure our container and tell it how to provide the concrete implementation.

1
2
_container = new Container();
_container.Configure(x => x.For<IFoo>().Use(() => new Foo("Hello")));

And the tests to verify it works :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Test]
public void IFoo_should_resolve_to_Foo()
{
var foo = _container.GetInstance<IFoo>();
foo.ShouldBeType<Foo>();
}
[Test]
public void message_should_be_set_during_construction()
{
var foo = _container.GetInstance<IFoo>();
foo.Message.ShouldBe("Hello");
}

Using Func<IContext, T>

There are other scenarios where not only do you want more control on a concrete types construction, but also need to resolve other dependencies. SM also allows you to specify a Func<IContext,T> where the IContext allows you to resolve classes from the container.

So if we have a scenario with an IBar and an IFoo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Bar : IBar
{
public IFoo Foo { get; set; }
}
class Foo : IFoo
{
}
interface IBar
{
IFoo Foo { get; }
}
interface IFoo
{
}

We can use the Func<IContext,T> similar to how we used the Func.

1
2
3
4
5
6
7
8
9
10
11
12
_container = new Container();
_container.Configure(x =>
{
x.For<IFoo>().Use<Foo>();
x.For<IBar>().Use(c =>
{
var bar = new Bar();
bar.Foo = c.GetInstance<IFoo>();
return bar;
});
});

And naturally our test to verify it works:

1
2
3
4
5
6
7
[Test]
public void should_set_foo_property_on_bar()
{
var bar = _container.GetInstance<IBar>();
bar.Foo.ShouldBeType<Foo>();
}

So that was a brief introduction into using Funcs to provide the concrete implementation of an interface for Structure Map.

All the Learning Structure Map code can be found in my Learning solution on Git Hub : http://github.com/RookieOne/Learning