StructureMap Implementation
From Logic Wiki
In MVC 5
- Get Structuremap package from NuGet
- Get Servicelocation package from NuGet
- Create folder DependencyInjection for Ioc Classes
- Copy the classes from old project ( DependencyScope, DependencyResolver)
- Copy DependencyScope and DependencyResolver into the folder ‘DependencyInjection‘
- Resolve classes names
- To resolve interface IDependencyScope Add references to
- System.Web.Http
- System.Web.Http.WebHost
- Create IocConfig (copy code from the old project)
- Resolve Dependencies
- Add IocConfig call to Global.asax.cs (reference newly created DependencyResolver Class)
protected void Application_Start()
{
var container = IocConfig.Setup();
System.Web.Mvc.DependencyResolver.SetResolver(new DependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new DependencyResolver(container);
- Different configurations for API project
- For API project you may not need this statement
System.Web.Mvc.DependencyResolver.SetResolver(new DependencyInjection.DependencyResolver(container));
- For static methods concrete object can be get using the similar statement given below
var storeService = IocConfig.Setup().GetInstance<IUserStoreService<ApplicationUser>>();
In MVC 6
- Create IoC project in solution
- install StructureMap.Microsoft.DependencyInjection nuget package in IoC project
- Add project references to IoC but not the UI ones
- create a class file and write the code below
public class InstanceScanner : Registry
{
public static IContainer Setup()
{
var container = new Container(
x =>
{
x.Scan(k =>
{
k.TheCallingAssembly();
k.WithDefaultConventions(); // if interface has I in front of implementation you don't need to define again
k.AssembliesFromApplicationBaseDirectory();
});
// x.For<ITest>().Use<Test>(); //If naming conventions are not implemented
}
);
return container;
}
}
- in UI (Main) project add IoC project reference
- in Startup.cs file
public IServiceProvider ConfigureServices(IServiceCollection services) // THIS CAN BE VOID BUT CHANGE IT TO RETURN IServiceProvider
{
// Add framework services.
services.AddMvc();
return ConfigureIoC(services);
}
public IServiceProvider ConfigureIoC(IServiceCollection services)
{
var container = InstanceScanner.Setup(); // referencing the code above
container.Populate(services);
return container.GetInstance<IServiceProvider>();
}
- That's it.
- If an interface is starts with "I" and class name you don't need to do anything.
- If naming conventions are not implemented uncomment the relevant part above.
Note :
For<MyContext>().Use(() => new MyContext("LocalhostConnString"));
If you give StructureMap an object instance, it will treat that instance as a singleton and return the same one every time. If instead you give it a lambda that creates an instance, it will run that lambda each time the type is requested.