Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterless constructor error with autofac in web api 2

I am using Autofac as IOC and here is my structure:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdTudent.Repo
{
    public interface IRepository
    {
        IAdvertisementRepository Advertisements { get; set; }
        IProfileRepository Profiles { get; set; }
    }
}

My repositories class is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdTudent.Repo
{
    public class Repositories : IRepository
    {
        public Repositories(IAdvertisementRepository advertisementRepository,
                            IProfileRepository profileRepository)
        {
            Advertisements = advertisementRepository;
            Profiles = profileRepository;
        }
        public IAdvertisementRepository Advertisements { get; set; }
        public IProfileRepository Profiles { get; set; }
    }
}

And my startup class is:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
         var builder = new ContainerBuilder();

        builder.RegisterType<Repositories>().As<IRepository>();
        builder.Register<IGraphClient>(context =>
        {
            var graphClient = new GraphClient(new Uri("http://localhost:7474/db/data"));
            graphClient.Connect();
            return graphClient;
        }).SingleInstance();
        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        //builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
       
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}
    

and here is my account controller:

public class AccountController : ApiController
{
    private  IRepository _repository;
    private const string LocalLoginProvider = "Local";
    private ApplicationUserManager _userManager;
    private IGraphClient _graphClient;
   

    public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }       

    public AccountController(IRepository repository, IGraphClient graphClient,
         ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
    {
        
        AccessTokenFormat = accessTokenFormat;
        _repository = repository;
        _graphClient = graphClient;

    }
}

but I always this problem

"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

I searched on the internet but I couldn't find anything that can help can anyone guide me?

like image 501
Mehran Ahmadi Avatar asked Sep 06 '15 05:09

Mehran Ahmadi


2 Answers

Per the WebApi OWIN documentation:

A common error in OWIN integration is use of the GlobalConfiguration.Configuration. In OWIN you create the configuration from scratch. You should not reference GlobalConfiguration.Configuration anywhere when using the OWIN integration.

It looks like you have a couple of issues:

  1. The HttpConfiguration needs to be newed up when using OWIN.
  2. You are missing the UseAutofacWebApi virtual method call.

You also need the Autofac WebApi OWIN package as per the docs.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);
    }
}
like image 65
NightOwl888 Avatar answered Nov 11 '22 23:11

NightOwl888


Check your Global.asax.cs. You should remove this line if you have it:

GlobalConfiguration.Configure(WebApiConfig.Register);

You can move this to Startup.cs Configuration like this:

WebApiConfig.Register(config);
like image 41
Ihor Avatar answered Nov 11 '22 22:11

Ihor