Autofac Web API错误确保控制器具有无参数的公共构造函数

时间:2018-02-16 05:50:27

标签: asp.net asp.net-web-api autofac ioc-container

使用ASP.NET WebAPI配置Autofac时出现此错误。

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

Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var file = HostingEnvironment.MapPath("~/log4net.config");
        if (file != null)
        {
            var configFile = new FileInfo(file);
            if (configFile.Exists)
                XmlConfigurator.ConfigureAndWatch(configFile);
            else
                BasicConfigurator.Configure();
        }
        else
        {
            BasicConfigurator.Configure();
        }

        var builder = new ContainerBuilder();

        var config = new HttpConfiguration();

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

        builder.RegisterWebApiFilterProvider(config);
        builder.RegisterModule(new WebModule(app));

        // Register your MVC controllers.
        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        // OPTIONAL: Register model binders that require DI.
        builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
        builder.RegisterModelBinderProvider();

        // OPTIONAL: Register web abstractions like HttpContextBase.
        builder.RegisterModule<AutofacWebTypesModule>();

        // OPTIONAL: Enable property injection in view pages.
        builder.RegisterSource(new ViewRegistrationSource());

        // OPTIONAL: Enable property injection into action filters.
        builder.RegisterFilterProvider();

        // register config
        builder.Register(ct => config).AsSelf().SingleInstance();
        HelpPageConfig.Register(config);

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

        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseAutofacMvc();
        WebApiConfig.Register(config);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
        config.EnsureInitialized();
    }
}

的Global.asax.cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

WebModule.cs

public class WebModule : Module
{
    private readonly IAppBuilder _app;

    public WebModule(IAppBuilder app)
    {
        _app = app;
    }

    protected override void Load(ContainerBuilder builder)
    {
        // ----  Utilities -----------------------------------
        builder.RegisterType<Log4NetLogger>()
            .As<ILogger>().SingleInstance();
        builder.RegisterType<DataAccessConfigurationSettings>()
            .As<IDataAccessSettings>().SingleInstance();
        builder.RegisterType<ApplicationServicesConfigurationSettings>()
            .As<IApplicationServicesSettings>().SingleInstance();
        builder.RegisterType<ValidationExceptionHandler>()
            .As<IExceptionHandler<ValidationException>>().SingleInstance();
        builder.RegisterType<SqlExceptionHandler>()
            .As<IExceptionHandler<SqlException>>().SingleInstance();
        builder.RegisterType<GeneralExceptionHandler>()
            .As<IExceptionHandler<Exception>>().SingleInstance();


        // ----  Business ------------------------------------
        builder.RegisterType<UserBusiness>()
            .As<IUserBusiness>().InstancePerRequest();

        // ----  Validator -----------------------------------
        builder.RegisterType<UserSignupModelValidator>()
            .AsSelf().SingleInstance();

        // ----  Controllers -----------------------------------
        builder.RegisterType<DeflateCompressionActionFilter>()
            .AsWebApiActionFilterFor<UserController>().InstancePerRequest();



        base.Load(builder);
    }
}

UserController.cs

[RoutePrefix("api/User")]
public class UserController : ApiController
{
    private readonly IUserBusiness _userBusiness;

    public UserController(IUserBusiness userBusiness)
    {
        _userBusiness = userBusiness;
    }
    ...
}

我相信我错过了一些我不知道的小事,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

看看这个答案:MVC Web API not working with Autofac Integration

也许您只需要像上面的链接中所述对容器进行设置即可

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = 
     new AutofacWebApiDependencyResolver(container);

从理论上讲,您会获得不同的例外,但情况也可能如此。