10

我正在尝试使用 ASP.NET WebAPI 设置 Castle Windsor。

我也在使用 Hyprlinkr 包(https://github.com/ploeh/Hyprlinkr),因此需要将一个 HttpRequestMessage 实例注入到我的控制器的依赖项之一中。

我正在关注 Mark Seemann 的这篇文章 - http://blog.ploeh.dk/2012/04/19/WiringHttpControllerContextWithCastleWindsor.aspx,但我发现虽然 API 运行,但当我调用它时,请求只是挂起。没有错误信息。就好像它处于一个无限循环中。它挂在我的自定义 ControllerActivator 中对 Resolve 的调用

我在想我的一些城堡注册错误。如果我删除了上面文章中提到的那些,那么我可以成功调用 API(尽管没有我需要解决的依赖关系)

有任何想法吗?

代码如下

//Global.asax
public class WebApiApplication : HttpApplication
{
    private readonly IWindsorContainer container;

    public WebApiApplication()
    {
        container = 
            new WindsorContainer(
                new DefaultKernel(
                    new InlineDependenciesPropagatingDependencyResolver(), 
                    new DefaultProxyFactory()), 
                new DefaultComponentInstaller());

        container.Install(new DependencyInstaller());
    }

    protected void Application_Start()
    {        
        GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorCompositionRoot(this.container));
    }

// installer
public class DependencyInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.AddFacility<TypedFactoryFacility>();

        container.Register(
            Component.For<ValuesController>()
                .Named("ValuesController")
                .LifeStyle.PerWebRequest,

            Component.For<IResourceLinker>()
                .ImplementedBy<RouteLinker>()
                .LifeStyle.PerWebRequest,

            Component.For<IResourceModelBuilder>()
                .ImplementedBy<ResourceModelBuilder>()
                .LifeStyle.PerWebRequest,

                Component.For<HttpRequestMessage>()
                .Named("HttpRequestMessage")
                .LifeStyle.PerWebRequest
            );
    }
}

//Activator

public class WindsorCompositionRoot : IHttpControllerActivator
{
    private readonly IWindsorContainer container;

    public WindsorCompositionRoot(IWindsorContainer container)
    {
        this.container = container;
    }

    public IHttpController Create(
        HttpRequestMessage request,
        HttpControllerDescriptor controllerDescriptor,
        Type controllerType)
    {
        var controller = (IHttpController)this.container.Resolve(controllerType, new { request = request });

        request.RegisterForDispose(
            new Release(
                () => this.container.Release(controller)));

        return controller;
    }

// DependencyResolver   
public class InlineDependenciesPropagatingDependencyResolver : DefaultDependencyResolver
{
    protected override CreationContext RebuildContextForParameter(CreationContext current, Type parameterType)
    {
        if (parameterType.ContainsGenericParameters)
        {
            return current;
        }

        return new CreationContext(parameterType, current, true);
    }
}

编辑****************附加信息****************

所以我设置了一个场景,控制器只将 HttpRequestMessage 作为 ctor 参数并发现:

这有效:

//controller
public class ValuesController : ApiController
    {
        private readonly HttpRequestMessage _httpReq;

        public ValuesController(HttpRequestMessage httpReq)
        {
            _httpReq = httpReq;
        }
//IHttpControllerActivator
public IHttpController Create(
            HttpRequestMessage httpRequest,
            HttpControllerDescriptor controllerDescriptor,
            Type controllerType)
        {

            var controller = (IHttpController)this.container.Resolve(
                controllerType, new { httpReq = httpRequest });

            return controller;

但是,这不是。

//controller
public class ValuesController : ApiController
    {
        private readonly HttpRequestMessage _httpReq;

        public ValuesController(HttpRequestMessage request)
        {
            _httpReq = request;
        }

//IHttpControllerActivator
public IHttpController Create(
            HttpRequestMessage request,
            HttpControllerDescriptor controllerDescriptor,
            Type controllerType)
        {

            var controller = (IHttpController)this.container.Resolve(
                controllerType, new { request = request });

            return controller;

即当匿名对象具有称为“请求”的属性并且控制器ctor arg称为“请求”时。它以某种方式使控制器认为它的请求属性为空。这就是导致我看到的错误的原因:

无法重用“ApiController”实例。'ApiController' 必须为每个传入消息构建。检查您的自定义“IHttpControllerActivator”并确保它不会制造相同的实例。

在 System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancelToken) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage 请求, CancellationToken cancelToken) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage请求,CancellationToken 取消令牌)

阅读此内容 如何在不调用 setter 注入的情况下丰富 StructureMap 中的对象组合?

它解释了一个类似的场景。

当然,hyprlinkr 的 HttpRequestMessage 的 ctor arg 称为“request”,所以我确实需要使用该属性名称指定 anon 对象。

有任何想法吗?

4

2 回答 2

13

这是一个适合我的组合根:

public class WindsorCompositionRoot : IHttpControllerActivator
{
    private readonly IWindsorContainer container;

    public WindsorCompositionRoot(IWindsorContainer container)
    {
        this.container = container;
    }

    public IHttpController Create(
        HttpRequestMessage request,
        HttpControllerDescriptor controllerDescriptor,
        Type controllerType)
    {
        var controller = (IHttpController)this.container.Resolve(
            controllerType,
            new
            {
                request = request
            });

        request.RegisterForDispose(
            new Release(
                () => this.container.Release(controller)));
        return controller;
    }

    private class Release : IDisposable
    {
        private readonly Action release;

        public Release(Action release)
        {
            this.release = release;
        }

        public void Dispose()
        {
            this.release();
        }
    }
}

这是我创建容器的方式:

this.container =
    new WindsorContainer(
        new DefaultKernel(
            new InlineDependenciesPropagatingDependencyResolver(),
            new DefaultProxyFactory()),
        new DefaultComponentInstaller())
        .Install(new MyWindsorInstaller());

这是 InlineDependenciesPropagatingDependencyResolver:

public class InlineDependenciesPropagatingDependencyResolver : 
    DefaultDependencyResolver
{
    protected override CreationContext RebuildContextForParameter(
        CreationContext current,
        Type parameterType)
    {
        if (parameterType.ContainsGenericParameters)
        {
            return current;
        }

        return new CreationContext(parameterType, current, true);
    }
}

最后,这是我注册 RouteLinker 的方法:

container.Register(Component
    .For<RouteLinker, IResourceLinker>()
    .LifestyleTransient());

需要注意的一件事是 ApiController 基类有一个名为RequestHttpRequestMessage 类型的公共属性。正如我的书Windsor 的第 10.4.3 节中所解释的,如果每个可写属性具有匹配的组件,它将尝试为其分配一个值——并且该匹配不区分大小写。

当您将名为 HttpRequestMessage 的名称传递request给 Resolve 方法时,这正是发生的情况,因此您需要告诉 Castle Windsor 它应该放弃对 ApiControllers 的属性注入。以下是我在基于约定的注册中的做法:

container.Register(Classes
    .FromThisAssembly()
    .BasedOn<IHttpController>()
    .ConfigureFor<ApiController>(c => c.Properties(pi => false))
    .LifestyleTransient());
于 2012-10-23T00:06:24.480 回答
0

为什么不在 ASP.NET Web API 中使用已经内置的机制 - 依赖解析器

http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver

在项目 WebApiContrib 中有 CastleWindsor 解析器实现,但正如我在依赖解析器中看到的那样

https://github.com/WebApiContrib/WebApiContrib.IoC.CastleWindsor

正如马克在评论中所说 - 实现 IHttpControllerActivator 的方法之一

http://blog.ploeh.dk/2012/10/03/DependencyInjectionInASPNETWebAPIWithCastleWindsor.aspx

于 2012-10-20T06:05:11.720 回答