I have a Web Api app that consumes another REST Api client. I wrapped the REST API client into a service.

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;
            }
        }
    }
 ....

I am using AutoFac and injecting the service in the controller

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();
        }
    }

But I am getting this error.

An error occurred when trying to create a controller of type 'PostController'. Make sure that the controller has a parameterless public constructor.

Here is my 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;
        }

Can someone spot what I am missing here?

Thanks

Related posts

Recent Viewed