1

I was wondering if someone can suggest the best pattern to use in the above scenario, assuming that

A) StructureMap is used in the following way:

            cfg.For<ISession>()
                .LifecycleIs(new TransientLifecycle())
                .Use(ctx => ctx.GetInstance<ISessionFactory>().OpenSession());

B) I would like all method calls to various services/repositories within a single controller action wrapped inside a TransactionScope, meaning if any of the actions goes wrong, then none of them should be committed.

I read somewhere that the session must be constructed within the TransactionScope block if this were to work which in my case is not so given that session is injected within each repository by Structuremap.

Rok
  • 1,482
  • 3
  • 18
  • 37

1 Answers1

0

If you want more control over the scope of your ISession I would inject an ISessionFactory instead in your controllers and leave the ISession being injected in your repositories or inject a factory/factories to create your repository instance(s). This way in each controller action you could do something like:

using (var session = sessionFactory.OpenSession())
{
    // Do controller actions
    IMyRepository myRepository = repositoryFactory<IMyRepository>.Create(session);

    var myObject = myRepository.FindSomething();
    ...
}
Cole W
  • 15,123
  • 6
  • 51
  • 85
  • Hi Cole, I want to avoid passing the session parameter to the service+repository level. Moreover, repos should not be accessed directly from the controller. I would really like to find a way of doing it in a DI way. – Rok Mar 15 '16 at 07:13
  • @Rok everything I describe above uses DI so I'm not sure what you mean. What I'm suggesting is to remove the creation of repositories up front by your IOC container which is creating ISessions and leave that up to your controller using the factory pattern to create your repositories. This way you are creating your repositories in your controller action and injecting the ISession into it as you create it (within the controller action). – Cole W Mar 15 '16 at 11:38