views:

430

answers:

1

What is the required IOC instance lifecycle I need to use in conjuction with a NServiceBus message handler if I want an instance per message handled.

PerRequest won't work, since given the numerous constructor dependenices and dependency graph I have, it gives me many instances when I require only one per Handle(MessageX msg) call. I can't or don't want to inject it directly into the message handler since it is required further down the object graph. E.g. inject IPersonService, depends on IPersonRepository, they can be per request (Default), but IPersonDBContext need to be per message call.

PerThread won't work since NServiceBus uses the same worker threads over and over.

Singleton, HttpContext, etc.. are obviously not applicable.

Has anyone came across this with either StructureMap or Castle?

A: 

I might be missing something here, but PerRequest will give you a new instance for each MessageHandler ( the messagehandlers are them selves registered as PerRequest). I have just committed a fix for a bug that caused messagehandlers to fire multiple times for each message. I wonder if that bug has been misleading you (try to get the lastest 2.0 build from CI and see if that does it for you)

http://teamcity.codebetter.com/viewLog.html?buildId=7087&tab=artifacts&buildTypeId=bt96

Hope this helps!

Andreas Öhlund
True, if my IMessageHandler<Msg> depends on IPersonService, and IAnimalService, they are constr injected per request (default for most IOCs I believe), however lets say both IPersonService and IAnimalService depend on IDbContext, on PerRequest then I get 2 instances of IDbContext (for both other dependencies) rather than the one (it is one uow even if it interacts with 2 services/repos). In a web context, I can set IDbContext to HttpContext, and in a non-web threaded context I can set IDbContext per Thread. I can't see how I can achieve one IDbContext per Handle(msg) call.
mattcodes
The way we work around that inside NServiceBus is that we inject an ISessionFactory rather than ISession. We have a message module which manages the opening and closing of sessions on the session factory, and all the applicative code uses SessionFactory.GetCurrentSession()Hope that helps.
Udi Dahan