I'm having trouble scoping my IDocumentSession dependency with Ninject.
Every time my bus executes a command, I want a new IDocumentSession. Commandhandlers that are created by the factory should have that same instance of IDocumentSession injected. I thought putting the bus in a CallScope would work, but I think the AsFactory breaks the CallScope? How would I get this done?
public class Bus : IBus
{
private readonly ICommandHandlerFactory _factory;
private readonly IDocumentSession _session;
public Bus(ICommandHandlerFactory factory, IDocumentSession session)
{
_factory = factory;
_session = session;
}
public void ExecuteCommand<T>(T command) where T : class
{
var handler = _factory.Create<T>();
handler.Handle(command);
_session.SaveChanges();
}
}
public class ActivateAccountCommandHandler : ICommandHandler<ActivateAccountCommand>
{
private readonly IDocumentSession _session;
public ActivateAccountCommandHandler(IDocumentSession session)
{
_session = session;
}
public void Handle(ActivateAccountCommand command)
{
// Do something
}
}
kernel.Bind<IDocumentStore>().ToMethod(ctx => DocumentStore.Get()).InSingletonScope();
kernel.Bind<IDocumentSession>().ToMethod(ctx => ctx.Kernel.Get<IDocumentStore>().OpenSession());
kernel.Bind<ICommandHandlerFactory>().AsFactory();
kernel.Bind<IBus>().To<Bus>().InCallScope();
I also tried with context preservation but this makes no difference.
kernel.Bind<IDocumentSession>().ToMethod(ctx => ctx.ContextPreservingGet<IDocumentStore>().OpenSession());