更新时间: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?
安装有水管,使这项工作的NuGet包StructureMap.MVC5。
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);