AutoFac不注册api控制器 [英] AutoFac does not register api controller

查看:218
本文介绍了AutoFac不注册api控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AutoFac来注册api控制器,但不知道出了什么问题

I am using AutoFac to registered api controller but don't know whats the problem

遇到错误

Type 'myApp.WebAPI.Controllers.myController' does not have a default constructor

我添加了以下IocHelper类

I added IocHelper class as below

public class IocHelper {
public static IContainer CreateContainer() {

        var builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

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

谢谢.

推荐答案

    Please refer the below solution, and also make sure you declared the injected interfaces as public explicitly.
    //Global.asax file -Application Start method
    protected void Application_Start()
    {
             var bootStrapApp = new BootstrapApplication()
            .ConfigureRoute(GlobalConfiguration.Configuration)
            .ConfigureContainer(new ContainerBuilder(), GlobalConfiguration.Configuration);
    }

    // BootstrapApplication.cs class file

    public class BootstrapApplication
    {
       public BootstrapApplication ConfigureRoute(HttpConfiguration httpConfiguration)
       {

          httpConfiguration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
          return this;
       }

      public BootstrapApplication ConfigureContainer(ContainerBuilder container, HttpConfiguration httpConfiguration)
      {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(n => n.FullName.StartsWith("<projectNamespacevalue>")).ToArray();
        //projectNamespacevalue for ex. AspNet.WebApi2.Demo 
        // var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(n => n.FullName.StartsWith("AspNet")).ToArray();

        container.RegisterAssemblyTypes(assemblies).AsImplementedInterfaces();
        container.RegisterApiControllers(assemblies); //WebApi controllers scanning and registration
        var ioccontainer = container.Build();
        httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(ioccontainer);      
        return this;
    }
}

这篇关于AutoFac不注册api控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆