ServiceLocatorImplBase.cs 未找到

ServiceLocatorImplBase.cs not found

当客户端调用我的 WebAPI 控制器时,我 运行 出现以下错误:

ServiceLocatorImplBase.cs 未找到错误

'Microsoft.Practices.ServiceLocation.ActivationException' 类型的异常发生在 Microsoft.Practices.ServiceLocation.dll 但未在用户代码中处理

WebAPI 控制器使用构造函数注入来注入应由 StructureMap IoC 解析的存储库依赖项。有趣的是,相同的代码 运行 在我的另一台开发机器上运行良好。这是我的堆栈跟踪。感谢您的帮助。

System.ArgumentNullException was unhandled by user code
HResult=-2147467261
Message=Value cannot be null.
Parameter name: httpContext
Source=System.Web
ParamName=httpContext

堆栈跟踪:

at System.Web.HttpContextWrapper..ctor(HttpContext httpContext)
at WebApi2.DependencyResolution.StructureMapDependencyScope.get_HttpContext() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 69
at WebApi2.DependencyResolution.StructureMapDependencyScope.get_CurrentNestedContainer() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 55
at WebApi2.DependencyResolution.StructureMapDependencyScope.DisposeNestedContainer() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 90
at WebApi2.DependencyResolution.StructureMapDependencyScope.Dispose() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 85
at WebApi2.App_Start.StructuremapMvc.End() in c:.........\WebApi2\App_Start\StructuremapMvc.cs:line 44

您 运行 遇到的问题是因为您试图在应用程序组成的时间点解决 HttpContext(通常在 Application_Start 事件中完成 Global.asax). HttpContext 是应用程序 运行时状态 的一部分。它是 null 正在编写应用程序的时间点。

它似乎在您的开发环境中工作的原因可能是因为您的开发环境的应用程序池在经典模式下是 运行。其他环境很可能(正确地)运行 处于集成模式。所以,这是一个设计问题,而不是您可能期望的部署问题。

解决方案是使用 Abstract Factory,这样您就可以将 HttpContextWrapper 的实例化推迟到运行时。然后,您可以将抽象工厂而不是 HttpContextWrapper 注入到您的服务中。

public interface IHttpContextFactory
{
    HttpContextBase Create();
}

public class HttpContextFactory
    : IHttpContextFactory
{
    public HttpContextBase Create()
    {
        return new HttpContextWrapper(HttpContext.Current);
    }
}

有关包括用法在内的完整示例,请参阅 this answer and

感谢您的回复。两台机器都是运行集成模式。该错误确实具有误导性,使我走错了路。我花了几个小时试图找到这个 ServiceLocatorImplBase.cs 所在的位置。我碰巧查看了深层嵌套的内部异常,发现最内部的异常(第 5 层)抱怨 POCO 生成器生成的某些实体没有身份密钥。这是因为我手动添加了一些实体之间的外键关系

public virtual RelatedEntity1 {get;set;}
public virtual RelatedEntity2 {get;set;}

没有在相关实体中设置 [key] 属性。我不确定这是否可以解决,但异常消息不应将人们引向错误的轨道。