tags:

views:

27

answers:

2

Is it possible to pass the requesting type as a parameter when configuring a StructureMap container.

For example:

            container.Configure(x => {
                x.For<ILogger>().Use(new TestLogger(log.Add, requestingType));         
            });

Where requesting type is the consuming object's type:

public class SomeClass
{
    private readonly ILogger logger;
    public SomeClass(ILogger logger)
    {
        this.logger = logger;
    }
}

So the type passed to the logger would be SomeNamespace.SomeClass.

Thanks, Ben

A: 

I found a solution here

Basically we changed the ILogger interface to ILogger<T> and made use of the generic type inference feature in StructureMap.

Strictly speaking this doesn't answer my question of whether I can get the requesting type so if you know how to do this please respond - it would be useful to know.

Ben
A: 

First I want to point out a potential gotcha, registering an instance with Use(new Type()) causes that instance to be registered as a singleton. To avoid this, you can do Use(() => new Type()).

Here is how you get the requested type at configuration time:

container.Configure(x => {
  x.For<ILogger>().Use(c => new TestLogger(log.Add, c.Root.RequestedType));
});
Robin Clowers
@Robin, this returns the type of the instance being created, not the type requesting the instance. For example, requesting an ILogger from within an MVC controller, should pass the type of the controller. Hope that clarifies.
Ben
Ah I see, that makes a lot more sense. I don't know of a way to do that in StructureMap.
Robin Clowers