【问题标题】:Autofac: Type 'MyController' does not have a default constructorAutofac:类型“MyController”没有默认构造函数
【发布时间】:2016-07-01 07:08:31
【问题描述】:

我有一个使用另一个 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();
        }
    }

但是我收到了这个错误。

尝试创建类型控制器时出错 '后控制器'。确保控制器具有无参数 公共构造函数。

这是我的 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;
        }

有人能发现我在这里缺少什么吗?

谢谢

【问题讨论】:

标签: c# asp.net asp.net-web-api dependency-injection autofac


【解决方案1】:

我不见了

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

显然,控制器也需要注册。

【讨论】:

  • 这个,我在使用 OwinSelfHost 和 autofac 时遇到了 HTTP 404 错误,直到我手动注册了我的控制器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2023-03-20
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多