我有一个使用另一个REST Api客户端的Web Api应用程序。我将REST API客户端包装到服务中。
myproj / services / PostDataService.cs public interface IPostDataService { Task<IList<Post>> GetAllPosts(); } public class PostDataService : IPostDataService { private static IDataAPI NewDataAPIClient() { var client = new DataAPI(new Uri(ConfigurationManager.AppSettings["dataapi.url"])); return client; } public async Task<IList<Post>> GetAllPosts() { using (var client = NewDataAPIClient()) { var result = await client.Post.GetAllWithOperationResponseAsync(); return (IList<Post>) result.Response.Content; } } } ....
我正在使用AutoFac并将服务注入到控制器中
myproj / controllers / PostController.cs public class PostController : ApiController { private readonly IPostDataService _postDataService; public PostController(IPostDataService postDataService) { _postDataService = postDataService; } public async Task<IEnumerable<Post>> Get() { return await _postDataService.GetAllPosts(); } }
但我收到此错误。
尝试创建类型为“ PostController”的控制器时发生错误。确保控制器具有无参数的公共构造函数。
这是我的Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { ContainerConfig.Configure(); GlobalConfiguration.Configure(WebApiConfig.Register); } } public static class ContainerConfig { private static IContainer _container; public static IContainer GetContainer() { if (_container != null) return _container; var builder = new ContainerBuilder(); builder.RegisterType<PostDataService>() .AsSelf() .InstancePerLifetimeScope() .AsImplementedInterfaces(); _container = builder.Build(); return _container; } public static IContainer Configure() { var container = GetContainer(); var webApiResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = webApiResolver; return container; }
有人可以发现我在这里缺少的东西吗?
谢谢