If you are using StructreMap to resolve the dependencies in the ASP.NET MVC 5 application then Steve Smith’s blog post Resolving Dependencies in ASP.NET MVC 5 with StructureMap can be a great help for you. I have followed Steve’s blog to use the StructureMap. I am summarizing the steps as follows:
Using the Nuget Package Manager add package of StructureMap.mvc5 in the project
Refactor controller to use the constructor injection.
If you are following the default convention means IMovieRepository should be resolved to MovieRepository then you should not care about any other files. However you can override default behavior in the DefaultRegistry class which is inside DependencyResolution folder. As you notice below that StructureMap is scanning with default convention.
An Important Note
Example shown in Steve blog is using Repository from same MVC project. What if Repository is not part of the same MVC project, in this case you need to explicitly specify in the StructureMap DefaultRegistry class that scan the assembly containing the Repository. This can be specified as follows:
As you see that we are explicitly specifying that the scan assembly which contains MovieRepository. In this case MovieRepository is part of another project MvcMovie.Infrastructure.MovieRepository. Other important class is StructuremapMvc which is inside App_Start folder.
This is all you need to configure to resolve dependency using StructureMap in the ASP.NET MVC application.
Happy Coding.
Very helpful article, I was stuck on DI with ASP.NET MVC5 with StructureMap.MVC5. Quick look at your article saved my sunday. Great work. Keep helping. God bless you!
Hi,
My application has 3 layer web,Business and service.Web is MVC 5 application.Controller has reference of business layer.My interface and its implementation lies in business layer.I have used the solution you have provided but I am still facing the same issue.Can you please help me with the error.
“No parameterless constructor defined for this object”
Wow…the line scan.AssemblyContainingtype saved me! Thank you so much…