嗨,我有一个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.Controllers.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控制器。简单控制器工作良好。
builder.Build()
之前,您需要调用builder.RegisterApiControllers
... - nemesv