1

I am trying to get the StructureMap 3 current container has follows:

public HomeController(IContainer injectedContainer) {

  IContainer container = new Container();

  var test1 = container.GetAllInstances(typeof(IMediator)); 
  var test2 = injectedContainer.GetAllInstances(typeof(IMediator));

}

test1 returns nothing ... test2 returns a mediator instance.

So my StructureMap 3 configuration is working fine but in some places of my application I need to get the container manually. How can I do that?

I tried the following:

var test3 = ObjectFactory.Container.GetAllInstances(typeof(IMediator));

But this returns also an empty value.

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • *...just curious, why have you deleted question with my answer? was it wrong? just curious...* – Radim Köhler Feb 20 '15 at 15:54
  • By mistake ... I had two windows opened and deleted the wrong question. Then I tried to recover it but was not able. Do you know if that is possible? – Miguel Moura Feb 20 '15 at 16:20
  • No idea, at least I append vote to undelete... ;) anyhow, mostly wanted be sure, that my answer helped a bit... Because that's the way (syntax) I am using for setter injection `x.Policies.SetAllProperties ( set => set.TypeMatches ( type => type.GetInterfaces().Any(i => i.IsEquivalentTo(typeof(ISetting)))` ... good luck with structure map anyhow ;) ( – Radim Köhler Feb 20 '15 at 16:27

1 Answers1

4

All you're doing in your example is creating an empty container, this is why nothing is being returned. You can see this by calling container.WhatDoIHave(); on your container.

First of all you have to configure your container like so:

IContainer container = new Container();
container.Configure(c =>
{
    c.IncludeRegistry<WebsiteRegistry>();
});

WebsiteRegistry.cs

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.Scan(x =>
        {
            x.TheCallingAssembly();
            x.WithDefaultConventions();
        });
    }
}

Then you'll be able to access your instances within ObjectFactory. However, as you've probably noticed the ObjectFactory is marked for removal in future releases of StructureMap so you have a few options available to you.

A common recommendation if you're using ASP.NET MVC is to use child containers that are bound to your web applications HTTP Context (see this tutorial for how it can be done, or this Nuget package that uses the same approach).

If you need to access the container manually then using this approach you're able to pull an instance of your child container from HttpContext.Items that gets disposed of at the end of the request.

Another option is to look at creating your own instance of the ObjectFactory, like this example.

Community
  • 1
  • 1
Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63