I'm confused about the proper way to manage my DbContext
lifetime using dependency injection in my WinForms application. Right now, I have code that looks like the following
static class Program
{
// This is the main window's controller, which stores all the
// dependencies that are resolved in the composition root and handles
// passing those dependencies to other objects
private static IMainController mainController;
private static void ComposeDependencies
{
UnityContainer container = new UnityContainer();
container.RegisterType<IMyContext, MyContext>();
container.RegisterType<IOrderRepository, OrderRepository>();
container.RegisterType<IOrderService, OrderService>();
mainController = new MainController(
container.Resolve<IOrderService>());
}
}
public class OrderRepository : IOrderRepository
{
private readonly IMyContext context;
public OrderRepository(IMyContext context)
{
this.context = context;
}
}
public class OrderService : IOrderService
{
private readonly IOrderRepository repository;
public OrderService(IOrderRepository repository)
{
this.repository = repository;
}
}
public class MainController
{
private readonly IOrderService orderService;
public MainController(IOrderService orderService)
{
this.orderService = orderService;
}
public void DoSomethingWithAnOrder()
{
FirstTypeOfController controller = new FirstTypeOfController(this.orderService);
// Show window, assign controller, etc.
}
public void DoSomethingElseWithAnOrder()
{
SecondTypeOfController controller = new SecondTypeOfController(this.orderService);
// Show window, assign controller, etc.
}
}
The problem I'm having is that this pattern results in all of my repositories getting created when my program starts, so the MyContext
instances stay around through the whole program. So when the database gets updated outside of my program, my program doesn't see the new data because MyContext
is using references to the data that it already has loaded.
If this were a web application, then I'd have new dependencies made with every request, but since this is WinForms, I don't understand how to get around this problem while keeping a single composition root and without passing my Unity container all around my program (or having a static reference to it) so that each controller can resolve its own per instance dependencies.
What's the standard solution to this problem, and is there something that I'm doing incorrectly with how/where I'm composing my dependencies or using my DbContext
?
I know that MVC is meant more for web applications and something like MVVM or MVP is perhaps more suited to non-web, but those would both have this same problem with a single composition root that only gets called once.