Skip to content

Instantly share code, notes, and snippets.

@kenkam
Created August 4, 2016 09:48
Show Gist options
  • Save kenkam/a0c66ef82d93f4f98e0030a81eaf2c80 to your computer and use it in GitHub Desktop.
Save kenkam/a0c66ef82d93f4f98e0030a81eaf2c80 to your computer and use it in GitHub Desktop.
using Castle.MicroKernel.Lifestyle;
using Castle.Windsor;
using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using Library.Api.Web;
namespace Library.Api.Windsor
{
public class WindsorControllerActivator : IHttpControllerActivator
{
private readonly IWindsorContainer container;
public WindsorControllerActivator(IWindsorContainer container)
{
this.container = container;
}
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
var scope = container.BeginScope();
SetHttpRequestMessage(request);
var controller = (IHttpController) container.Resolve(controllerType);
request.RegisterForDispose(new Release(scope, () => container.Release(controller)));
return controller;
}
private void SetHttpRequestMessage(HttpRequestMessage request)
{
var context = container.Resolve<OwinContextProvider>();
context.Current = request.GetOwinContext();
}
private class Release : IDisposable
{
private readonly IDisposable scope;
private readonly Action release;
public Release(IDisposable scope, Action release)
{
this.scope = scope;
this.release = release;
}
public void Dispose()
{
scope.Dispose();
release();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment