我正在自托管 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 相关