Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Created July 24, 2013 15:00
Show Gist options
  • Save davidwhitney/6071383 to your computer and use it in GitHub Desktop.
Save davidwhitney/6071383 to your computer and use it in GitHub Desktop.
Ninject scope hacking for RSE
public class NinjectActivation : IHandlerActivationStrategy
{
private readonly IEventHandlerResolver _eventHandlerResolver;
private readonly IKernel _singleKernel;
private readonly ConcurrentDictionary<object, IKernel> _scopes;
public NinjectActivation(IKernel singleKernel)
{
_eventHandlerResolver = new EventHandlerResolver();
_singleKernel = singleKernel;
_scopes = new ConcurrentDictionary<object, IKernel>();
}
public IEnumerable<IHandle<TEventType>> GetHandlers<TEventType>()
{
var types = _eventHandlerResolver.GetHandlerTypesForEvent(typeof(TEventType));
foreach (var type in types)
{
if (type == typeof (IHandleAsync<TEventType>))
{
var scope = _singleKernel.BeginScope();
var instance = (IHandle<TEventType>) scope.Get(type);
_scopes.AddOrUpdate(instance, x => scope, (y, z) => scope);
yield return instance;
}
else
{
yield return (IHandle<TEventType>) _singleKernel.Get(type);
}
}
}
public void OnHandlerExecuted<TEventType>(IHandle<TEventType> handler)
{
IKernel scope;
_scopes.TryGetValue(handler, out scope);
if (scope != null)
{
scope.Dispose();
}
}
}
public interface IKernel : IDisposable
{
object Get(Type type);
IKernel BeginScope();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment