且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获得StructureMap与AngularJs / MVC5和WebApi2 Web项目

更新时间:2023-02-24 11:40:08

这是发生,因为依赖分辨率不是为的WebAPI控制器的工作。 StructureMap没有找到构造函数,不能解决IThingRepository。

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和MVC的工作方式不同,具有略微不同的依赖解析机制。在Global.asax codeDependencyResolver.SetResolver适用于MVC,但不是的WebAPI。那么,我们如何得到这个工作?

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. 安装有水管,使这项工作的NuGet包StructureMap.MVC5。

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

安装封装StructureMap.MVC5

Install-Package StructureMap.MVC5

创建一个新的StructureMapDependencyResolver类为MVC和的WebAPI

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);
    }
}


  • 更​​新在Global.asax code:

  • 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);
    


  • 有关发生了什么检查这个博客帖子的完整说明ASP.NET MVC 4,网络API和StructureMap