如何在Web API和MVC混合应用程序中使用Autofac解析Web API控制器

本文关键字:API Web Autofac 控制器 解析 混合 MVC 应用程序 | 更新日期: 2023-09-27 18:26:23

嗨,我有一个MVC应用程序,在那里我定义了一些对Web API的依赖关系。

public class AutofacWebApiDependenceResolver : IDependencyResolver
{
    private readonly IComponentContext container;
    public AutofacWebApiDependenceResolver(IContainer container)
    {
     if (container == null)
     {
         throw new ArgumentNullException("container");
     }
     this.container = container;
    }
    public object GetService(Type serviceType)
    {
        if (serviceType == null)
        {
            throw new ArgumentNullException("serviceType");
        }
        var ret = this.container.ResolveOptional(serviceType) ;
        return ret;
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {            
        if (serviceType == null)
        {
            throw new ArgumentNullException("serviceType");
        }            
        Type enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);
        var ret = (IEnumerable<object>)this.container.ResolveOptional(enumerableType);
        return ret;
    }
}

然后在我的引导程序类中,我在Application_Start中调用它,如下所示:

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependenceResolver((IContainer)container);

当我调试代码时,我可以看到我的DependencyResolver已经注册了所有服务,但我仍然收到以下错误:

出现错误。键入"WebApp.Controller.AuthenticateController"没有默认的构造函数

这是我的控制器的代码:

public class AuthenticateController : ApiController
{
    private readonly IFormsAuthenticationService formsAuthenticationService;
    private readonly IMemberShipProvider memberShip;
    private readonly IDataService dataService;
    public AuthenticateController(
        IMemberShipProvider memberShip,
        IFormsAuthenticationService formsAuthenticationService, IDataService dataService)
    {
        this.memberShip = memberShip;
        this.formsAuthenticationService = formsAuthenticationService;
        this.dataService= dataService;
     }
}

如何将参数带到api控制器。Simple控制器工作正常。

如何在Web API和MVC混合应用程序中使用Autofac解析Web API控制器

我建议使用以下方法在MVC和WebApi的应用程序中实现这一点。

首先,您的项目需要参考以下

  • Autofac
  • Autofac.WebApi
  • Autofac.Mvc5(更改末尾的数字以匹配您的aspnetmvc版本)

然后在您的Autofac注册中,您将需要以下内容来注册MVC和WebApi控制器以及您需要的任何其他注册。然后将Container连接到MVC DI和WebApi DI。

var builder= new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly()); //Register MVC Controllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers
//Register any other components required by your code....
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Set the MVC DependencyResolver
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver

我希望这能有所帮助。

nemesv的指导完成了的任务

builder.RegisterApiControllers(Assembly.GetExecutingAssembly())

调用builder.Build() 之前调用builder.RegisterApiControllers