How can I inject multiple repositories in a NServicebus message handler?

Posted by Paco on Stack Overflow See other posts from Stack Overflow or by Paco
Published on 2010-03-24T16:08:34Z Indexed on 2010/03/25 8:03 UTC
Read the original article Hit count: 372

I use the following:

public interface IRepository<T>
{
   void Add(T entity);
}

public class Repository<T>
{
  private readonly ISession session;

  public Repository(ISession session)
  {
    this.session = session;
  }

  public void Add(T entity)
  {
     session.Save(entity);
  }
}

public class SomeHandler : IHandleMessages<SomeMessage>
{
  private readonly IRepository<EntityA> aRepository;
  private readonly IRepository<EntityB> bRepository;

  public SomeHandler(IRepository<EntityA> aRepository, IRepository<EntityB> bRepository)
  {
    this.aRepository = aRepository;
    this.bRepository = bRepository; 
  }

  public void Handle(SomeMessage message)
  {
   aRepository.Add(new A(message.Property);
   bRepository.Add(new B(message.Property);
  }
}

public class MessageEndPoint : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
   public void Init()
   {
      ObjectFactory.Configure(config =>
        {
            config.For<ISession>()
                .CacheBy(InstanceScope.ThreadLocal)
                .TheDefault.Is.ConstructedBy(ctx => ctx.GetInstance<ISessionFactory>().OpenSession());
            config.ForRequestedType(typeof(IRepository<>))
                .TheDefaultIsConcreteType(typeof(Repository<>));
   }
}

My problem with the threadlocal storage is, is that the same session is used during the whole application thread. I discovered this when I saw the first level cache wasn't cleared. What I want is using a new session instance, before each call to IHandleMessages<>.Handle. How can I do this with structuremap? Do I have to create a message module?

© Stack Overflow or respective owner

Related posts about nservicebus

Related posts about nhibernate