Search code examples
.netdependency-injectioninversion-of-controlioc-containern-tier-architecture

Does DI make sense in a desktop app?


I am about to create a Desktop App (with .NET windows forms)

Essentially, I want to create an n-tier app but I also want loose coupling between layers. However, I am not very sure if this is a good approach for windows forms

And now I just wonder if it would be really a wise choice to use any IoC (StructureMap, Ninject, Spring.Net), I have used them before for Asp.Net web applications but what makes me doubt now is the fact that working with windows forms my business entities will persist when I navigate through tabs and unlike than web forms or mvc apps where it would be necesary to inject my business entity for every new request that is performed, I mean this because of the Asp.Net page life cycle where is performed the initialization and controls instantiation.

This it is kind of a long-term development project, it combines maintenance tracking, inventory, work orders, and management reporting. I am currently working on a proposal for its architecture.

Maybe I am misunderstanding the point of using an IoC, so please tell me what do you think would be a better choice?

Any point of view would be appreciated.


Solution

  • It still makes sense to use DI / IoC in your case, because it's all about surrendering control of where the dependencies come from, who manages their life-time, etc.

    In that sense, the principle Inversion of Control is pretty much platform independent, it may work slightly differently in terms of wire-up between ASP.NET and WinForms, but the principal is the same.

    So whereas in ASP.NET typically the Inversion of Control is typically realised via Dependency Injection and mostly via Constructor Injection into Controllers, etc, that doesn't mean you have to follow the same pattern in Windows Forms - for example, you could just make a global instance of your IoC Container available to all Forms, and have them get their depdendencies via something like

    var SomeBusinessObject = container.Get<SomeBOType>(); //Ninject style.
    

    In this case it's still IoC (the form doesn't directly create the dependency, it has no idea if the container is giving it a brand new instance, or a single static instance that's globally shared, it doesn't know when it will be destroyed, etc) but it's not strictly speaking Dependency Injection - however you gain all of the benefits of having complex dependency graphs managed for you by the IoC framework.

    Also bear in mind that you can always handle the event where the user switches tabs, and treat that as though it were a brand new "request", throwing away and re-getting your dependencies then, if for some reason that is important for how the app should work.