AutoFac MVC Web API

2019-09-03 07:35发布

I have a simple AutoFac example working but now want to apply this to my web api project AND have the correct separation between the layers.

The issue I am seeing is the standard controller x "does not have a default constructor" but i am stumped so asking for advice..

I am calling RegisterApiControllers as well as RegisterControllers..

this is what I have in my DependencyInjectionContainer

public static class DependencyInjectionContainer
{
    public static ContainerBuilder Builder;
    public static IContainer Container;

    public static void Init(Assembly mainAssembly)
    {
        Builder = new ContainerBuilder();
        var config = GlobalConfiguration.Configuration;

        RegisterTypes(mainAssembly);

        Container = Builder.Build();

        config.DependencyResolver = new AutofacWebApiDependencyResolver(Container);
        DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
    }

    private static void RegisterTypes(Assembly mainAssembly)
    {
        var roomBookingConnectionString = ConfigurationManager.ConnectionStrings["RoomBooking"].ConnectionString;

        Builder.RegisterControllers(mainAssembly);

        Builder.RegisterType<RoomRepository>().As<IRoomRepository>().WithParameter(new TypedParameter(typeof(string), roomBookingConnectionString));
        Builder.RegisterType<RoomService>().As<IRoomService>();

        Builder.RegisterApiControllers(mainAssembly);

        Builder.RegisterFilterProvider();
    }
}

I am calling this in my Global.asax.cs

DependencyInjectionContainer.Init(typeof(MvcApplication).Assembly);

One big assumption here is that this is correct...

Builder.RegisterApiControllers(mainAssembly);

edit---------------------------------------------------------------------

I have just tried moving all of the DI registrations etc in the 2 methods above back to the global.asax.cs and it works!?!?

I think its something to do with the 'RegisterApiControllers'. I am passing the calling assembly into the above init method using 'typeof(MvcApplication).Assembly'. Is there something wrong with this?

Thanks.

1条回答
看我几分像从前
2楼-- · 2019-09-03 07:54

The RegisterApiControllers method is used by Autofac to locate the controllers.

When you do Builder.RegisterApiControllers(mainAssembly); are you sure the mainAssembly parameter is the assembly containing the controllers?

Anyway, if you have this kind of problems, you can do something like this (guessing you have a controller called RoomBookingController) :

builder.RegisterApiControllers(typeof(RoomBookingController).Assembly);

This way Autofac will locate the assembly containing your controller, no matter where it is.

查看更多
登录 后发表回答