无法解析 Web Api 控制器中的依赖项

Can't resolve dependencies in Web Api Controller

我有一个 Web Api 与 owin 和 Windsor。

获取下一个错误:

An error has occurred.An error occurred when trying to create a controller of type 'DBManagerController'. Make sure that the controller has a parameterless public constructor.System.InvalidOperationException at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()An error has occurred.Type 'Swissphone.SolutionKit.Utilities.DbInit.DataManager.WebHost.Controllers.DBManagerController' does not have a default constructorSystem.ArgumentException at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

奇怪,因为我注册了所有的依赖。

这是我的启动 class:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var httpContext = HttpContext.Current;
        var hibernateConfigFileName = string.Empty;
        if (httpContext != null)
        {
            hibernateConfigFileName = httpContext.Server.MapPath(Properties.Settings.Default.HibernateConfigFile);
        }
        else
        {
            throw new InvalidOperationException("When using IIS hosting, HttpContext.Current must not be NULL");
        }
                    var windsorContainer = new WindsorContainer();

        windsorContainer.Install(new ContextInstaller(), new DbInitInstaller());

        var configuration = new HttpConfiguration() { DependencyResolver = new WindsorResolver(windsorContainer) };


        configuration.Routes.MapHttpRoute("DBManager",
            "api/{controller}/{action}/{id}",
            new { id = RouteParameter.Optional });


        app.UseWebApi(configuration);
    }
}

安装人员:

public class ContextInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IUserContext>().ImplementedBy<UserContext>(),
            Component.For<ITenantContext>().ImplementedBy<TenantContext>());

    }
}


public class DbInitInstaller : IDbInitInstaller
{

    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IDbInitManager>().ImplementedBy<DbInitManager>());
    }
}

控制器:

public class DBManagerController : ApiController
{
    private IDbInitManager _manager;

    public DBManagerController(IDbInitManager manager)
    {
       _manager = manager;
    }

    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

Class 我无法解决:

public class DbInitManager : IDbInitManager
{
    public DbInitManager()
    {}
}

我在向控制器发出请求时出错。无法解析 IDbInitManager。

有没有人知道这是错误的,为什么注册的依赖关系没有得到解决?

不,您没有注册所有依赖项。

基本上,发生的事情是您没有在您的容器中明确注册您的控制器。 Windsor 尝试为您解析未注册的具体类型,但由于它无法解析它(由您的配置错误引起),因此它 return 为 null。它被强制为 return null,因为 Web API 由于 IDependencyResolver 合同而强制它这样做。由于 Windsor return 为 null,Web API 将尝试自己创建控制器,但由于它没有默认构造函数,因此将抛出 "Make sure that the controller has a parameterless public constructor" 异常。此异常消息具有误导性,并未解释真正原因。

您可以为您的控制器添加另一个安装程序:

public class ControllersInstallers : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
                            .BasedOn<IHttpController>()
                            .LifestylePerWebRequest());
    }
}

必须显式注册必须从 Windsor 解析的每个依赖项。