【问题标题】:Type 'Api.Controllers.' does not have a default constructor输入“Api.Controllers”。没有默认构造函数
【发布时间】:2015-05-02 04:13:02
【问题描述】:

我有一个使用依赖注入的控制器:

   public FeedController(IFeedProcessor feedProcessor)
        {
            _feedProcessor = feedProcessor;
        }

这是我的配置代码:

public static void Config()
    {

        ObjectFactory.Initialize(x => x.Scan(scan =>
            {
                x.For<IFeedProcessor>().Use<FeedProcessor>();
            }));
    }

我的 FeedProcessor 类有参数构造函数:

 public FeedProcessor(IFeedParserFactory ifeedParserFactory)
        {
            _ifeedParserFactory = ifeedParserFactory;
        }

这个 StructureMapControllerFactory :

    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
                if (requestContext.HttpContext.Request.Url != null)
                    throw new InvalidOperationException(string.Format("Page not found: {0}", requestContext.HttpContext.Request.Url.AbsoluteUri.ToString(CultureInfo.InvariantCulture)));
            return ObjectFactory.GetInstance(controllerType) as Controller;
        }
    }

我得到这个错误: 类型“Api.Controllers.FeedController”没有默认构造函数 我该如何为这种情况配置结构图?

【问题讨论】:

  • 请将您的代码发布在哪里设置依赖解析器!
  • 你的 IFeedParserFactory(FeedController 的依赖)注册正确了吗?

标签: c# asp.net-mvc dependency-injection asp.net-web-api


【解决方案1】:

WebApi 不使用DefaultControlFactory 创建 Api 控制器的实例。相反,它使用DefaultHttpControllerSelector。但是,除非您有特定的原因要创建控制器工厂,否则我会改用 MVC 中内置的 Dependency Resolver 系统。

http://buchanan1966.tumblr.com/post/2192279804/mvc3-using-dependencyresolver-with-structuremap

http://marisks.net/2012/08/19/configuring-structuremap-in-aspnet-webapi/

【讨论】:

    【解决方案2】:

    我最终得到了这个异常,因为我在我的应用程序中的几个类中有循环依赖。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 2015-06-02
      • 2017-10-04
      相关资源
      最近更新 更多