Reputation: 39374
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.
Upvotes: 1
Views: 1979
Reputation: 9281
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.
Upvotes: 4