0

我有一个简单的应用程序,它使用 OWIN-Startup 类进行自我配置。但是,我无法让它工作!这是我的配置:

public void Configuration(IAppBuilder appBuilder) {

    var httpConfiguration = new HttpConfiguration();

    httpConfiguration.Routes.MapHttpRoute(
          name: "default_api_versioned_by_areas",
          routeTemplate: "api/{area}/{controller}/{action}/{id}",
          defaults: new { id = RouteParameter.Optional }
      );

    var container = new Container();

    // registering my services. They're all good....

    container.WithWebApi(
        httpConfiguration, new[] {GetType().Assembly});
    container.RegisterWebApiControllers(
        httpConfiguration, new[] { GetType().Assembly });

    appBuilder.UseDryIocWebApi(httpConfiguration)
        .UseDryIocOwinMiddleware(container);

    appBuilder.UseWebApi(httpConfiguration);

    // I can resolve other services:
    var s = container.Resolve<MyOtherService>();

    // but I cannot resolve controllers:
    var c = container.Resolve<ContentController>();
}

如您所见,MyOtherService是可解决的;但不是ContentController. 此外,当我请求 API 时,我收到此错误:

尝试创建“ContentController”类型的控制器时发生错误。确保控制器有一个无参数的公共构造函数。

谷歌搜索没有帮助。你能帮我弄清楚如何运行该应用程序吗?

更新:

似乎控制器根本没有注册。当我尝试解决-具有无依赖ContentController的默认值时 - 我收到此错误:ctor

// code:
var c = container.Resolve<ContentController>();

// exception:

An exception of type 'DryIoc.ContainerException' occurred in DryIoc.dll but was not handled in user code

Additional information: Unable to resolve MyProject.Areas.Alpha.Controllers.ContentController

Where CurrentScope: 

  and ResolutionScope: 

  and Found registrations:

  without matching scope DefaultKey.Of(0),{ID=33, ImplType=MyProject.Areas.Alpha.Controllers.ContentController, Reuse=CurrentScopeReuse {Name="WebRequestScopeName", Lifespan=100}}}

  without matching scope DefaultKey.Of(1),{ID=37, ImplType=MyProject.Areas.Alpha.Controllers.ContentController, Reuse=CurrentScopeReuse {Name="WebRequestScopeName", Lifespan=100}}}
4

2 回答 2

1

当框架无法解析控制器时,这是 Web API 中的标准错误响应。无法解析控制器的依赖项之一。

例如,如果 ContentController定义为

public class ContentController : ApiController {

    public ContentController(IOtherService service) { ... }

}

并且 DependencyResovler 不知道如何解决IOtherService,则将显示上述错误。

确保控制器的所有依赖项都已注册并且可以由 IoC 容器解析。

于 2017-01-21T15:26:19.580 回答
1

要找到控制器未解析的确切错误,您可以将throwIfUnresolved参数传递给WithWebApi方法。默认情况下,控制器的解析回退到 WebApi 基础设施并且原始异常被吞没。

container = container.WithWeApi(config, assemblies, throwIfUnresolved: type => type.Name.EndsWith("Controller"));

于 2017-01-21T18:29:51.193 回答