Bryan
Bryan

Reputation: 3541

Can't create controller, dependency injection

I have the following Startup file (Startup.cs):

public void Configuration(IAppBuilder app)
{


    AutofacConfig.RegisterIoc();
    HttpConfiguration config = new HttpConfiguration();

    ConfigureOAuth(app); //This must come first before we load the WebApiConfig below.

    WebApiConfig.Register(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(config);

}

As you can see, I register the autofac config. The code for my autofac config looks like this:(AutofacConfig.cs)

 public class AutofacConfig
    {
        public static void RegisterIoc()
        {
            var builder = GetBuilder();
            var container = builder.Build();

            // Set dependency resolver for MVC
            //DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container));

            // Set dependency resolver for Web API
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }

        public static ContainerBuilder GetBuilder()
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //builder.RegisterFilterProvider();


            var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(x => x.FullName.Contains("API")).ToArray();
            builder.RegisterAssemblyTypes(assemblies)
                .AsImplementedInterfaces()
                .InstancePerRequest();

            return builder;
        }
    }

But when I run my application and tries to access a method in my controller, I get the following error:

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

I have tried to debug my startup.cs either to see if it's executed, and it does.

Before I used to register autofac in Global.asax, but because I use OAuth, I moved away from Global.asax and created a Startup-file instead. I guess it has something to do with this?

My controller look like this:

private readonly IItemModelService _itemModelService;

public DataController(IItemModelService itemModelService)
{
    this._itemModelService = itemModelService;
}

Stacktrace:

at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext() at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

Upvotes: 3

Views: 474

Answers (1)

Bryan
Bryan

Reputation: 3541

I'm using Oauth with OWIN, and I did not know that It was a special implementation of autofac for owin based application.

My startup.cs looks like this and it works:

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


        //AutofacConfig.RegisterIoc();
        HttpConfiguration config = new HttpConfiguration();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(x => x.FullName.Contains("API")).ToArray();
        builder.RegisterAssemblyTypes(assemblies)
            .AsImplementedInterfaces()
            .InstancePerRequest();

        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        ConfigureOAuth(app); //This must come first before we load the WebApiConfig below.

        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

    }

I followed this links:

https://autofaccn.readthedocs.io/en/latest/integration/webapi.html#owin-integration

https://autofaccn.readthedocs.io/en/latest/integration/owin.html

Upvotes: 1

Related Questions