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 の構成を抽象化できるクラスです (したがって、IIS でホストされている API のバージョンの Global.asax 内で使用できます)。

ここに抜粋があります:

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' のコントローラーを作成しようとしたときにエラーが発生しました。コントローラーにパラメーターなしのパブリック コンストラクターがあることを確認してください。 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