Model-View-Presenter framework: In which project should the interfaces live? - c#

I'm dabbling with the MVP design framework, and I currently have my solution set out as follows:
Project: MODEL
Contains: Concrete object class, DataRetrieval class, IDataRetrieval interface
Project: PRESENTER
Contains: Presenter class, IView interface
Project: VIEW
Contains: View class, Program class
I've been revisiting this solution when I can, but now I can't remember why I've got the interfaces distributed as they are. It doesn't seem right. I tried the following:
Move the interfaces into the relevant project for the classes that
implement them.
Move both interface to the presenter class.
Making either of these changes is going to require a little work, so I just wondered if either answer is better than the other (or perhaps both are very, very wrong :))
If it matters, this is designed in C#.
I'd love to hear your opinions!
Andy

Im just done with my custom MVP framework on Winforms. From my experience I can clearly identify the following sub-projects for any MVP implementation
Model Project
View Interfaces Project
Presenter Interfaces Project (It can sit along with the view interfaces as well)
Presenter Implementation Project
View Implementation Project (This is where your Winforms/WPF/ASP.NET stuff goes)
Application Controller (This is an important and often overlooked aspect of the MVP. It is responsible for starting the entire framework including the application itself. It also manages cross presenter communication and navigation)
Application Navigator (The navigator dishes out the concrete views and presenters when
demanded by the application controller)

I would like to suggest you add a separate project to your solution and call it YourSolutionName.Contracts. Move there all your View and Model interfaces, so your Presenter project won't have dependencies from these two assemblies (for more details check dependency inversion principle).

Related

Application(solution) structure for Model View Presenter(+ Passive View) in WinForms?

Once upon a time I wrote a code that, with time, started to smell. It was not coded in a way that it could be easily tested. There were tight coupling on each of the children windows with database-centric Microsoft controls (like BindingNavigator, etc). But then it came the day when I was tired of my own code as it was not reusable, testable, or understandable (even by myself).
After reading about better ways to split presentation from business logic and database access/persistence, I came up with the first big change. I was then able to call a presenter for the children forms of my, let’s say, “MainForm”.
Nowadays, I have a bunch of Presenters, Views, Repositories, Models and Interfaces which I would like to organize in a “standard” project structure (i.e. projects like Business, Model, UI, Test). Can somebody expose such a structure, and, if possible, example folders they use inside each of them?
Also, should I use an only-one “MainPresenter”? or is it better to have one for each children form I will use, for example:
var searchReceivalPresenter = new SearchReceivalsPresenter(
new SearchReceivalsForm { MdiParent = this }, new SearchReceivalsRepository());
In my opinion I should keep several presenters.
Thanks in advance,
I think there may be some misunderstanding of MVP here - I wrote an article about how to do MVP with Windows Phone 7, but I cover the basics of MVP, and you should be able to understand the general theory and then apply it to WinForms:
Developing WP7 apps using the MVP pattern
But to quickly answer your question, every Form should implement a View interface, and every Presenter should handle 1 and only 1 View interface.
Where it gets tricky with WinForms is when you want to open a child Form. What I ended up doing is having the parent Presenter directly call a Show method on the child Presenter. The child Presenter would then use Dependency Injection to instantiate an implementation of the related View interface.
UPDATE (because I didn't fully answer the question) :)
Let me describe a project structure i've used for a winforms/MVP app:
/ - solution root
/[App]Core - project that contains the Model - pure business logic
/[App]Core/Model - data model (lowercase "m"), POCOs
/[App]Core/Daos - data access layer (all interfaces)
/[App]Core/Services - business logic classes (interfaces and implementations)
/[App]Ui - project that contains all UI-related code, but is UI-agnostic
/[App]Ui/Model - contains POCOs that are used by the UI but not the Core
/[App]Ui/Presenters - contains presenters
/[App]Ui/Views - contains view interfaces
/[App][Platform] - project that contains all UI-specific code (e.g. WinRT, WinPhone, WinForms, WPF, Silverlight, etc)
/[App][Platform]/Daos - implementation of DAO interfaces defined in [App]Core
/[App][Platform]/Services - implementation of business logic interfaces defined in [App]Core
/[App][Platform]/Views - implementation of view interfaces defined in [App]Ui
Is that more like what you were asking for?

Some architecture and design guidance regarding PRISM and WPF

I have a few questions regarding WPF MVVM application development with PRISM framework:
Should modules in a modular application contain data access code ?
If modules depend on code present in an infrastructure project like the "Stock Trader RI" in the prism documentation does, wouldn't that cause tight coupling between those modules and the infra. project, aren't modules suppose to be self contained functionality !?
I like the DDD (Domain Driven Development) mythology that all code should depend on the business logic layer, thus no "dependency arrows" should go out of the BLL, instead they should go into the BLL (eg. the DAL depends on interfaces in the BLL and then you can use a DI Container to wire everything), and I think that the modules are the BLL of the application, so I don't want them depending on anything, can you achieve that in a modular PRISM app (how) ?
Yes, since a Prism application is usually only made up of modules, then if you want data accessed in your application you will have to access it from the modules in some manner.
Managing dependencies is important. I try to examine what my module does in order to decide whether it makes sense for it to reference my infrastructure project or not. For example, if you were creating an event logging module, you might want to consider putting that interface in a common library that isn't your infrastructure project, because you may re-use that for other projects. However, I do not mind my project specific modules referencing the infrastructure project. The modules still allow me to enforce loose coupling, swap out modules at will to add or remove features, or swap the UI if I were to slice the application horizontally instead of vertically.
I'm not quite sure what you mean by not depending on "anything". I imagine they still depend on the .NET core libraries. So what about Prism? Is that allowed? If you are concerned about them referencing Prism or your infrastructure project you could always have your BLL code in separate DLLS that your modules reference and implement the model repositories, view model logic, and view logic inside of.

WPF: MVP vs MVVM

What is the difference between MVP VS MVVM? Why we are using MVP even though we have three layers: business, data access and presentation? Is there any specific reason to divide the Presentation layer into MVP?
MVP and MVVM are both derivatives of MVC. MVC is a pattern that separates the user presentation and interaction from the internal representation.
This requires three layers, since tying the user interaction/presentation directly to the internal representation will cause both to bend to conform to each other. In your application, you described these layers as the Presentation, the Business layer, and the Data Access layer. With only those very loose descriptions, you could potentially be describing any of the MVC derivatives, or the original MVC pattern itself.
The key differences between each of the derivatives are the dependencies each layer takes on the other layers, and how tightly they are bound to each other. This article has some details on the differences, though of course it shouldn't be considered authoritative:
http://nirajrules.wordpress.com/2009/07/18/mvc-vs-mvp-vs-mvvm/
"... MVVM is attractive for platforms which support bi-directional binding with less effort. Also a minor tradeoff is ViewModel unlike Presenter can stand on its own (Presenter normally requires a View’s interface)."
We use at our company projects of WPF desktop application MVP instead of the built in MVVM for the main reason that in MVP the presenter is the main entry point that knows everything and no one knows about the presenter.
For each View the presenter which have one responsibility which is taking interactions from the IView interfaces by subscribing to events that the View triggers.
The presenter updates the View by a properties that encapsulates the internal View controls like TextBox with string properity and GridView with any Collection property. The constructor of the MainPresenter class will look something like this MainPresenter(IMainView, IEmployeeStore, IOtherDependency,..)
The Constructor of MainView class will look like this MainView(IPartialViewIfExists,..) that means the view does not know anything about the Presenter or anything else outside the View layer (which is the opposite of MVVM that enforces the MainView to directly couple the MainViewModel to automate the
two way databinding).
That clean loosely coupling architecture which the MVP provides is really powerful and flexible which enables the ability for the following:
Your application can replace the GUI with anytime without changing anything in the presenter, you can also change the GUI technology to something else like WinForms or something.
You can separate your GUIs in a separate project that doesn't require any dependencies of your main application like the presenters and dataAccesses
Your View can be used for any other application witch is useful for general GUIs.
You can unit test the views, the presenters and the data access classes easily.
The ViewModel in MVVM doesn't know about the View but I don't think that is helpful since it is responsible for the View. The View shouldn't know about the presenter which handles business logic and that's what exactly the MVP provides (or the way that we implement MVP).
That doesn't mean that MVVM is bad. MVVM is a good architecture and faster to code and easier to start with since it is already implemented in WPF and Xamarin but as I explained we prefer MVP for listed reasons.
In general MVP is cleaner and more scalable but requires more knowledge and coding experience and have to be implemented manually. MVVM is already there, it is easy to use and lets you implement faster but provides coupling and has some limitations. They all have their pros and cons and it depends on your need.

MVVM and avoiding Monolithic God object

I am in the completion stage of a large project that has several large components: image acquisition, image processing, data storage, factory I/O (automation project) and several others.
Each of these components is reasonably independent, but for the project to run as a whole I need at least one instance of each component. Each component also has a ViewModel and View (WPF) for monitoring status and changing things.
My question is the safest, most efficient, and most maintainable method of instantiating all of these objects, subscribing one class to an Event in another, and having a common ViewModel and View for all of this.
Would it best if I have a class called God that has a private instance of all of these objects? I've done this in the past and regretted it.
Or would it be better if God relied on Singleton instances of these objects to get the ball rolling.
Alternatively, should Program.cs (or wherever Main(...) is) instantiate all of these components, and pass them to God as parameters and then let Him (snicker) and His ViewModel deal with the particulars of running this projects.
Any other suggestions I would love to hear.
Thank you!
Take a look at some dependency injection frameworks such as Unity (which CAL uses), Castle Windsor or Spring.NET.
These concerns are taken care of quite nicely using Microsoft's "Composite Application Library" (aka Prism) a framework for developing composite WPF applications:
http://msdn.microsoft.com/en-us/library/ff647752.aspx
http://msdn.microsoft.com/en-us/library/ff648611.aspx
Composing your views: Prism has a concept of an application shell window and a region manager. The shell acts as a bare-bones layout page where you define named place-holder regions e.g. "MainMenu" and "TabInterface". You wrap references up to your views and viewmodels in module classes e.g. "MainMenuModule" and "TabInterfaceModule", and define which region the module should be associated with. Prism will create your views and inject them into the shell regions when the application starts. This allows you to compose your views independently of each other.
Communication between viewmodels: Prism supports a mediator pattern called the "Event Aggregator". Basically you can publish and subscribe to messages via the event agregator from your viewmodels. This allows viewmodels to loosely communicate via messages, rather than having to know about each other and hooking events.
Prism advocates and supports patterns for developing components independently of each other in a loosely coupled fashion, without introducing God objects and over coupling. A big part of Prism is also it's use of IOC and dependency injection, so unit testing becomes much easier too.
I found the following article a good practical introduction to using Prism and MVVM:
http://www.developmentalmadness.com/archive/2009/10/03/mvvm-with-prism-101-ndash-part-1-the-bootstrapper.aspx
My prefered way of getting ViewModels is using a ViewModelLocater. Basically it's the God object like you imply, but it's only responsibility is to create each ViewModel and keep a reference to it. I usually add the VML to the App's resources and each view is responsible for setting it's DataContext to the correct ViewModel. If you are subscribing multiple events you can either have your VML wire them up manually, or it can create the VM that throws the events first and pass it to the dependent VM in it's constructor.
You might use Controllers (ApplicationController, Use-Case Controllers) instead of a ‘God’ class. The controllers are responsible to create the ViewModel objects and they mediate between them.
How this works is shown by the WPF Application Framework (WAF) project.
I hope I have understood your question well. I think using a God ViewModel its not a good idea. its better to have a single viewmodel for each of your views and instantiate all the related viewmodels in that viewmodel. then you can use a mediator to send message between viewmodels of that view and other views, safly. also i propuse to use wpf commands instead of events. you can find a greate article about mediator in here.

Decoupling the view, presentation and ASP.NET Web Forms

I have an ASP.NET Web Forms page which the presenter needs to populate with controls. This interaction is somewhat sensitive to the page-life cycle and I was wondering if there's a trick to it, that I don't know about.
I wanna be practical about the whole thing but not compromise testability.
Currently I have this:
public interface ISomeContract
{
void InstantiateIn(System.Web.UI.Control container);
}
This contract has a dependency on System.Web.UI.Control and I need that to be able to do things with the ASP.NET Web Forms programming model. But neither the view nor the presenter may have knowledge about ASP.NET server controls.
How do I get around this? How can I work with the ASP.NET Web Forms programming model in my concrete views without taking a System.Web.UI.Control dependency in my contract assemblies?
To clarify things a bit, this type of interface is all about UI composition (using MEF). It's known through-out the framework but it's really only called from within the concrete view. The concrete view is still the only thing that knows about ASP.NET Web Forms. However those public methods that say InstantiateIn(System.Web.UI.Control) exists in my contract assemblies and that implies a dependency on ASP.NET Web Forms.
I've been thinking about some double dispatch mechanism or even visitor pattern to try and work around this but I don't yet know in which direction I want to go and I would really like some input on the matter.
Not sure how a visitor would solve the problem. But why not have your contracts look like this:
public interface ISomeContract
{
void InstantiateIn(IControl container);
}
with an IControl implementation, possibly in another assembly to keep your contract assembly clean, that wraps over the ASP.NET System.Web.Control, like:
public class AspnetControl : IControl
{
public AspnetControl(System.Web.Control control) { }
// IControl members that dispatch to control
}
Although there's a high likelihood that eventually IControl would end up looking very much like a System.Web.Control (and hence defeat the point of abstracting it in the first place), it'd still be very testable, and your view and presenters won't have to know a thing about ASP.NET.
One way you can decouple your contract from your web control is to have a separate writer that handles getting the information from ISomeContract and places it in your Control container. This could reside in an assembly that references both the contract assembly and System.Web.
I have been reading about agile techniques, tdd, unit testing, solid, design patterns and felt utterly powerless to bridge the gap from all this wonderful theory to asp.net webforms.
I had another go at trying to find a solution to this problem earlier today and found this article:
http://p2p.wrox.com/content/articles/testing-aspnet-webforms
It is an excerpt from a book which I thought would solve all my problems but this chapter is really just an introduction to the possibilities of implementing the MVP pattern in webforms and it concludes with saying that its not really practical. The rest of the book is about testing asp.net MVC as far as I gathered.
There is also this new project which aims to bring the love back to the webforms platform:
http://webformsmvp.com/
In "normal" ASP.NET web forms, your page/user control is technically "in charge" of the processing, and imposes its life-cycle on the code. The page is the Presenter and the View, whether you like it or not.
Most attempts to implement the MVP pattern in this environment simply add excess complexity to an already overly complex environment! Pretending that another class is the Presenter is just that... pretending. (In MVC web sites, the Controller truly does control the code, and the View does not, so this argument no longer applies.)
My recommendation is to let the view look after its own life-cycle, and let it invoke Repositories and Model classes to retrieve/save data and invoke commands.
In this approach, the Model classes do not need to know anything about System.Web. These same Model classes could then be used in future MVC web sites, or Silverlight, or as a web service for WPF applications, or embedded in a WPF application, etc. It is up to the View to determine how to implement (using Controls) the response/data it gets from the Model.
The Model classes can be tested as much as you like if you correctly set them up to support dependency injection.
Hope that helps!

Categories