AutoFac MVC Web API

情到浓时终转凉″ 提交于 2019-12-25 03:12:57

问题


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:


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.



来源:https://stackoverflow.com/questions/35775752/autofac-mvc-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!