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.
Leave a Reply