asolvent
asolvent

Reputation: 881

StructureMap, MVC and ObjectInstantiation

I am using StructureMap as DI with MVC 4. I am pushing certain objects in the constructor via StructureMap.

Following I have in the the bootstraper

 public static void ConfigureDependencies()
 {
        ObjectFactory.Initialize(IE =>
        {
            IE.UseDefaultStructureMapConfigFile = true;
        });
 }

Controller Factory is as following

 public class ControllerMyFactory : DefaultControllerFactory
 {
    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        return ObjectFactory.GetInstance(controllerType) as IController;
    }
 }

Then I am plugging this in Global.asax

 BootStrapper.ConfigureDependencies();
 ControllerBuilder.Current.SetControllerFactory(new ControllerMyFactory());

Following is one of my Controller

public class SomeController : Controller
{
    ISomeService service;
    public SomeController(ISomeService service)
    {
          this.service = service;
    } 
}

Now my problem is object Instantiation, which are being passed in the constructor. I used to construct this object like Following

ISomeService service = CommonGateway.GetChannnel<ISomeService>();

How do I plugin this with StructureMap? How do I change the way StructureMap will instantiate the objects?

Please let me know if I am not very clear?

Thanks,

A

Upvotes: 0

Views: 213

Answers (1)

Rob West
Rob West

Reputation: 5241

You just need to configure StructureMap to know about your ISomeService and how to instantiate it like this:

ObjectFactory.Initialize(IE =>
{
    IE.For<ISomeService>().Use(() => CommonGateway.GetChannel<ISomeService>() as ISomeService);
});

This will then call your factory method when instantiating your controller, because your controller is already being created by StructureMap.

Upvotes: 1

Related Questions