1

我正在自托管 WebApi 应用程序以进行一些集成测试。

我这样设置我的服务器:

var httpConfig = new HttpSelfHostConfiguration(BaseAddress);

new ApiServiceConfiguration(httpConfig)
    .Configure();

var server = new HttpSelfHostServer(httpConfig);
server.OpenAsync().Wait();
Server = server; //this is just a property on the containing class

ApiServiceConfiguration是一个允许我抽象 WebApi 配置的类(所以我可以在 Global.asax 中将它用于 IIS 托管版本的 api)

这是一个摘录:

public class ApiServiceConfiguration 
   {
       private readonly HttpConfiguration _httpConfiguration;

       public ApiServiceConfiguration(HttpConfiguration httpConfiguration)
       {
           _httpConfiguration = httpConfiguration;
       }

       public void Configure()
       {
           //setup routes
           RouteConfig.RegisterRoutes(_httpConfiguration.Routes);

           //setup autofac
           AutofacConfig.Setup(_httpConfiguration);

我的AutofacConfig.Setup静态方法只是:

public static void Setup(HttpConfiguration config)
{
    var builder = new ContainerBuilder();

    // Register the Web API controllers.
    builder.RegisterApiControllers(Assembly.GetAssembly(typeof(MyController)));

    // Register dependencies.

    // Build the container.
    var container = builder.Build();

    // Configure Web API with the dependency resolver.
    //notice config is passed in as a param in containing method
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}

但是,当我从单元测试中调用我的 api 时:

using (var client = new HttpClient(Server))
{
    var result = client.PostAsync(BaseAddress + "api/content/whatever"

    var message = result.Content.ReadAsStringAsync().Result;
}

消息的值为:

发生错误。","ExceptionMessage":"尝试创建“ContentController”类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)在 System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage 请求) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage 请求,CancellationToken cancelToken) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext( )","InnerException":{"

这向我表明 Autofac 控制器注册没有工作。

如果我在设置中的以下行上设置断点:

var server = new HttpSelfHostServer(httpConfig);

并使用即时窗口检查httpConfig.DependencyResolver它是否确实与 Autofac 相关

4

2 回答 2

1

您需要将 ContainerBuilder 和 DependencyResolver 移出静态类。您的实现正在使用后期绑定,并且 autofac 依赖解析器不会替换默认解析器。

您可以在错误消息中看到这一点:“确保控制器具有无参数的公共构造函数。”

默认解析器无法处理没有无参数构造函数的控制器,这是构造函数注入所必需的。

于 2015-07-28T14:15:47.220 回答
0

我有同样的问题。就我而言,问题在于使用Assembly.GetCallingAssembly(). 我想获取调用程序集并将其传递给 Autofac 以注册控制器。但是在发布模式下它不起作用。

阅读以下文章后:

http://www.ticklishtechs.net/2010/03/04/be-careful-when-using-getcallingassembly-and-always-use-the-release-build-for-testing/

我刚刚删除了 GetCallingAssembly 调用并替换为显式传递程序集,例如typeof(Startup).Assembly

于 2016-05-12T14:19:32.167 回答