How do I get StructureMap working with an AngularJs / MVC5 and WebApi2 web project

ε祈祈猫儿з 提交于 2019-11-28 21:52:01

This is happening because dependency resolution isn't working for the WebApi controller. StructureMap isn't finding the constructor and can't resolve the IThingRepository.

WebApi and MVC work differently and have slightly different dependency resolution mechanics. The Global.asax code "DependencyResolver.SetResolver" works for MVC but not for WebAPi. So how do we get this working?

  1. Install the nuget package StructureMap.MVC5 which has the plumbing to make this work.

    Install-Package StructureMap.MVC5

  2. Create a new StructureMapDependencyResolver Class that works for both MVC and WebApi

    public class StructureMapDependencyResolver : StructureMapDependencyScope, IDependencyResolver
    {
        public StructureMapDependencyResolver(IContainer container) : base(container)
        {
        }
        public IDependencyScope BeginScope()
        {
             IContainer child = this.Container.GetNestedContainer();
             return new StructureMapDependencyResolver(child);
        }
    }
    
  3. Update the Global.asax code:

    //StructureMap Container
    IContainer container = IoC.Initialize();
    
    //Register for MVC
    DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
    
    //Register for Web API
    GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
    

For a full explanation of what is happening check this blog post on ASP.NET MVC 4, Web API and StructureMap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!