问题描述
我正在尝试使用 StructureMap 来初始化从 ApiController 派生的 ValuesController,但我收到了一个异常消息:
Im trying to use StructureMap to initialize my ValuesController that derivate from ApiController but i'm getting an exception that says:
IControllerFactory '...CustomControllerFactory' 没有返回名称为 'api' 的控制器.
The IControllerFactory '...CustomControllerFactory' did not return a controller for the name 'api'.
这是代码..
public class CustomControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
return (Controller)ConcretizationsManager.GetInstance(controllerType);
}
}
基本上 ConcretizationsManager 是 StructureMap 的包装器.此方法对于 Controller 类型的 Controller 始终可以正常运行,但对于 APIController 则不能.
basically ConcretizationsManager is a wrapper of StructureMap..This method always runs ok for Controllers of Controller type, but for APIController dont.
有人能帮我找到正确的方向吗?非常感谢
Anyone to get me to the right direction?Very thanks
推荐答案
对于 Web API,我使用的是像这样的自定义 ServiceActivator(即不同的工厂然后用于 MVC):
For the Web API I am using Custom ServiceActivator like this (i.e. different factory then for MVC):
public class ServiceActivator : IHttpControllerActivator
{
public ServiceActivator(HttpConfiguration configuration) {}
public IHttpController Create(HttpRequestMessage request
, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = Factory.CreateInstance(controllerType) as IHttpController;
return controller;
}
}
Factory 是我的 Sturcturemap API 包装器
在 App_StartWebApiConfig.cs
中,我确实像这样注册:
And in the App_StartWebApiConfig.cs
I do register that like this:
config.Services.Replace(typeof(IHttpControllerActivator), new ServiceActivator(config));
这篇关于带有结构映射的 WebAPI + APIController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!