将Swashbuckle添加到项目会导致错误"确保控制器具有无参数的公共构造函数"

时间:2017-05-16 14:58:21

标签: c# .net castle-windsor swashbuckle

我有一个使用OWIN的项目。整个解决方案由五部分组成:

  1. 网络应用
  2. 核心
  3. 基础设施
  4. 的WebAPI
  5. 测试
  6. 该项目运作良好。

    最近,我打算在我的项目中大摇大摆。经过一番研究,我决定使用Swashbuckle。 https://github.com/domaindrivendev/Swashbuckle#custom-routes

    我通过将以下代码添加到我的Startup.cs来跟随其教程:

    HttpConfiguration Config = new HttpConfiguration();
    WebApiConfig.Register(Config);
    Config.EnableSwagger((c) =>
    {
        c.SingleApiVersion("v1", "Flynn Forms");
        c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
    }).EnableSwaggerUi();
    app.UseWebApi(Config);
    

    然后,我在http://localhost:22391/swagger/ui/index处完成了我的API文档。但是,我的所有API都停止了工作。我的控制器有错误,例如:

    An error occurred when trying to create a controller of type 'FormTemplateController'. Make sure that the controller has a parameterless public constructor.
    

    我没有无参数构造函数......但在添加Swashbuckle之前它运行良好。我搜索了这个错误,有人建议只添加一个无参数构造函数就可以解决这个错误。所以我的控制器变成了:

     [RoutePrefix("api/develop")]
    public class FormTemplateController : ApiController
    {
        private IFormTemplateService formTemplateService;
        public FormTemplateController()
        {
        }
    
        public FormTemplateController(IFormTemplateService formTemplateService)
        {
            this.formTemplateService = formTemplateService;
        }
        [Route("form/{formId}")]
        [HttpGet]
        public FormTemplateEntity GetActiveFormTemplateByformId(string formId)
        {
            FormTemplateEntity formTemplate = formTemplateService.GetActiveFormTemplateEntityByFormId(formId);
            return formTemplate;
        }
        ....(different APIs)
    }
    

    错误确实消失了。但我现在收到一个新错误,表明formTemplateService为null。

    我正在使用Castle Windsor作为我的项目的Inversion of Control容器。 Swashbuckle与Castle Windsor有些冲突吗?有没有人有同样的问题并获得解决方案?我不确定我是否提供了足够的背景信息。如果您需要更多信息,请将其留在评论中。

    谢谢。

1 个答案:

答案 0 :(得分:1)

尝试不同的方法后,我发现以下工作。 起初,我把代码:

HttpConfiguration Config = new HttpConfiguration();
WebApiConfig.Register(Config);
Config.EnableSwagger((c) =>
{
    c.SingleApiVersion("v1", "Flynn Forms");
    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
}).EnableSwaggerUi();
app.UseWebApi(Config);
在Startup.cs中的

因为我认为这是我的解决方案的入口。 然后,我注意到在我的WebApi部分中,我有一个名为WebApiConfig.cs的文件,它也配置了HttpConfiguration的实例。所以我将代码移到了这个文件中。 (因为那里已经有一个HttpConfiguration实例,你不必再创建它。)只需将以下代码放在那里:

Config.EnableSwagger((c) =>
{
    c.SingleApiVersion("v1", "Flynn Forms");
    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
}).EnableSwaggerUi();

问题解决了。