When creating a Visual Studio MVC Web API and you are using Structure Map 3 (see below for older version) you will need a couple of packages for things to wire up correctly or you will get an error that says, “No parameterless constructor defined for this object. ”
The packages you need are: StructureMap.MVC5, StructureMap.WebApi2
<package id=”StructureMap.MVC5” version=”3.1.1.134″ targetFramework=”net452″ />
<package id=”StructureMap.WebApi2” version=”3.0.4.125″ targetFramework=”net452″ />
Then in the basic template project you can use the ValueController to test and it should be that simple.
You will notice in the MVC WEB-API project a few more folders added, check out the DependencyResolution folder! If you are using DTOs, some type of BLL or Repository you will need to add mappings to the DefaultRegistry.cs file to wire up the mapping of Interfaces to concrete implementations.
What if you are using an older structuremap like version 2.0.50727?
Do the following:
Manually add a folder called DependencyResolver or whatever you like…
I added a class file called ServiceActivator.cs
Add the following lines of code:
public class ServiceActivator : IHttpControllerActivator { public ServiceActivator(HttpConfiguration configuration) { } public IHttpController Create(HttpRequestMessage request , HttpControllerDescriptor controllerDescriptor, Type controllerType) { var controller = ObjectFactory.GetInstance(controllerType) as IHttpController; return controller; } }
Then add the following to the Global.ascx file
HttpConfiguration config = GlobalConfiguration.Configuration; config.Services .Replace(typeof(IHttpControllerActivator), new ServiceActivator(config));
I then add another file in the DepedencyResolver folder called BootstrapStructuremap.cs
This is where I linkup my interfaces to my concretes
public class BootstrapStuctureMap { private static bool _hasStarted; public static void Bootstrap() { new BootstrapStuctureMap().BootstrapStructureMap(); } public static void Restart() { if (_hasStarted) { ObjectFactory.ResetDefaults(); } else { Bootstrap(); _hasStarted = true; } } public void BootstrapStructureMap() { _hasStarted = true; ObjectFactory.Initialize(x => { x.PullConfigurationFromAppConfig = false; x.Scan(y => { y.Assembly(Assembly.GetAssembly(typeof(IWebAccess))); etc... etc... } ); }); } }
Then back in my global.ascx I add
protected void Application_BeginRequest() { try { BootstrapStuctureMap.Bootstrap(); } catch (Exception ex) { throw; } }
code-ON
Warren LaFrance