6

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?

peterh
  • 11,875
  • 18
  • 85
  • 108
Mehran Ahmadi
  • 311
  • 1
  • 3
  • 10

3 Answers3

7

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);
    }
}
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • I don't need for MVC controllers I just need web api controller as I mentioned above, do you have any idea? – Mehran Ahmadi Sep 06 '15 at 06:15
  • You are also not registering your global filters in the correct order. You need to call `builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);` before you call `builder.Build();`. See my example above. – NightOwl888 Sep 06 '15 at 06:18
  • I edited the code as you said but the same result as before, do you have any further idea? – Mehran Ahmadi Sep 06 '15 at 06:52
  • Thanks alot for your help I have the same error bud in stacktrace I don't have any problem in autofac it seems that problem is in other part,can you help me one more time? I also installed Autofac Web Api Owin package – Mehran Ahmadi Sep 06 '15 at 12:29
1

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);
Ihor
  • 184
  • 1
  • 3
0

You haven't told Autofac how to create an ISecureDataFormat<AuthenticationTicket> instance.

Add this in your startup class before your call builder.Build().

builder.RegisterType<ISecureDataFormat<AuthenticationTicket>>().As<TicketDataFormat>();
Angel Yordanov
  • 3,112
  • 1
  • 22
  • 19