我在ASP.NET Core API中找不到IHttpControllerActivator

时间:2019-08-20 10:23:58

标签: asp.net api core

我在asp.net核心api中找不到IHttpControllerActivator

 public class WindsorHttpControllerActivator:IHttpControllerActivator
{
    public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        var instance = DependencyContainer.Resolve(controllerType);

        if (instance == null)
        {
            throw new HttpException((int)HttpStatusCode.NotFound, string.Format("{0} cannot be resolved.", controllerType.Name));
        }

        return (IHttpController) instance;
    }
}

1 个答案:

答案 0 :(得分:0)

让我知道此重写是否有效。 第三方DI的API进行了更改

using Castle.Windsor;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;

public class WindsorControllerActivator : IControllerActivator
{
    private readonly IWindsorContainer _container;

    public WindsorControllerActivator(IWindsorContainer container)
    {
        _container = container;
    }

    public object Create(ControllerContext context)
    {
        var controllerType = context.ActionDescriptor.ControllerTypeInfo.AsType();
        var instance = _container.Resolve(controllerType);

        if (instance == null)
        {
            //throw whatever
        }

        return (ControllerBase)instance;
    }

    public void Release(ControllerContext context, object controller)
    {
        _container.Release(controller);
    }
}

这些文章至少对我有帮助:

https://kristian.hellang.com/third-party-dependency-injection-in-asp-net-core/

https://medium.com/@nevsnirG/manual-controller-activation-and-dependency-injection-in-asp-net-core-web-api-46aba579b0e

编辑: 在“''Startup.cs'''中,不要忘记这些行

services.AddSingleton<IControllerActivator>(new WindsorControllerActivator (_container));