Castle windsor and IHttpHandler and IHttpHandlerFactory

我的未来我决定 提交于 2019-12-08 02:03:52

问题


I'm developing a RIA application where there is javascript on the client (i'm using Ext) and .NET on the server, for json-rpc I'm using Jayrock which is a nice library (at least for me) as it is simple and works well, Ive used it in the past.

Jayrock uses Web Handlers to serve the json-rpc request, you code a class that implements IHttpHandler and derives from a Jayrock class with some attributes, and it does the rest to provide a javascript class to the browser to do its magic.

Now, normally web handlers will have parameter-less constructors, but I want to use DI on them, and use windsor to resolve the dependencies for me

So, I will have some class like the following

    public class VistaEntidadSimpleServer :  JsonRpcVistaHandler ,IHttpHandler
{
    public VistaEntidadSimpleServer(ISomeDependecy someObject)
    {
                 someObject.doSomething();

    }


    [JsonRpcMethod("Aceptar")]
    public string Aceptar (IVista vista)
    {
        throw new NotImplementedException ();
    }


    [JsonRpcMethod("Cancelar")]
    public string Cancelar (IVista vista)
    {
        throw new NotImplementedException ();
    }


    public IVista CargarDatos(IVista vista)
    {
        throw new System.NotImplementedException();
    }

}

So, now the problem is how to get windsor in the middle to do the resolving. After searching around, and from what it seems to do spring, I think I can give a try to IHttpHandlerFactory, and code something like this

    public class CastleWindsorHttpHandlerFactory : IHttpHandlerFactory
{
    public CastleWindsorHttpHandlerFactory ()
    {
        if (container==null)
        container=(IWindsorContainer)HttpRuntime.Cache.Get("Container");
    }

    #region IHttpHandlerFactory implementation

    public IHttpHandler GetHandler (HttpContext context, string requestType, string url, string pathTranslated)
    {
        return container.Resolve<IHttpHandler>(url);
    }

    public void ReleaseHandler (IHttpHandler handler)
    {
        container.Release(handler);
    }

    #endregion

    private static IWindsorContainer container=null;
}

Configuring the web app to use the factory for ashx files, and creating the container in global.asax, configuring the handlers with the url as ids, and registering the containter into the web cache.

Do you think this is a nice solution?, or is there something I am missing here, is there another way to get web handlers resolved by the container?

Thanks in advancce


回答1:


Instead of storing the container in cache, implement IContainerAccessor in your global HttpApplication to reference your container. No need to store a reference in CastleWindsorHttpHandlerFactory.

Other than that, it looks good.



来源:https://stackoverflow.com/questions/5384355/castle-windsor-and-ihttphandler-and-ihttphandlerfactory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!