autofacc: Type 'MyController'没有默认构造函数

本文关键字:默认 构造函数 MyController autofacc Type | 更新日期: 2023-09-27 17:53:52

我有一个使用另一个REST Api客户端的Web Api应用程序。我把REST API客户端包装成一个服务。

myproj/服务/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/控制器/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;
        }

有人能发现我在这里错过了什么吗?

谢谢

autofacc: Type 'MyController'没有默认构造函数

我错过了

builder.RegisterApiControllers(typeof(PostController).Assembly).

显然,控制器也需要注册