Search code examples
structuremapstructuremap3

Getting Reference to StructureMap Container


I'm new to StructureMap and have a scenario where I would like to get a handle to the container.

I am building a Web API service initializing StructureMap container in Application_Start of Global.asax

IContainer container = IoC.Initialize();
GlobalConfiguration.Configuration.DependencyResolver = new MyDependencyResolver(container);

But want to access container within my controllers to get instances to objects in the container.

I know I can call container.GetInstance and specify the type to get, but since I am not using ObjectFactory and initialized the container in Global.asax, I don't know a way to access it within my controllers.

What is the best way of passing the reference to container from Global.asax to rest of the application code?

Thanks, Jay.


Solution

  • Just add IContainer dependendy in the controller's constructor.

    public class MyController : IController
    {
        private readonly IContainer container;
    
        public MyController(IContainer container)
        {
            this.container = container;
        }
    
        [HttpPost]
        public ActionResult Execute(ViewModel viewModel)
        {
            var someType = this.container.GetInstance<ISomeType>();
        }
    }