score:3

My suggestion is to use dependeny injection (or inversion of control - depends how would you like to call it). I use myself castle windor. Really simple to integrate with mvc.net. read more

When IoC is up and running create ContextManager. Somethig like this:

public class ContextManager : IContextManager
{
    private XContext context;

    public XContext GetContext()
    {
        return context ?? (context = XContext.Create());
    }
}

Set IContextManager lifestyle as perwebrequest and you got yourself context that you can access from repositories and services. and it's same per one request.

EDIT

You also have to create your own controllerFactory

then you can use your services and repositories like this:

public class MyController : Controller
{
    public ISomeService SomeService { get; set; }
    public IContextManager ContextManager { get; set; }

...

}

You dont have to create new instances for services and repositories and you can manage those objects lifestyle from configuration. Most reasonable would be singleton


Related Articles