Created
July 24, 2013 15:00
-
-
Save davidwhitney/6071383 to your computer and use it in GitHub Desktop.
Ninject scope hacking for RSE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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