Learning PRISM – Modularity
Background
Modularity is not a new concept! Here is the official Microsoft definition:
Modularity is designing a system that is divided into a set of functional units (named modules) that can be composed into a larger application. A module represents a set of related concerns. It can include components, such as views or business logic, and pieces of infrastructure, such as services for logging or authenticating users. Modules are independent of one another but can communicate with each other in a loosely coupled fashion.
If you have used WPF for a while you may think that this is a little redundant… You can divide your UI into UserControls and then compose them at runtime, so what advantage does PRISM give us here? Good question, let’s start with the basics and work our way up…
public classSimpleModule : IModule
{
private readonly IRegionManager _regionManager;
publicSimpleModule(IRegionManager regionManager)
{
_regionManager = regionManager;
}
public voidInitialize()
{
// Do something here...
}
}
This is the simplest module you can possible create. To qualify as a Module, you have to implement the IModule interface. The IModule interface defines 1 method: void Initialize()
[NOTE] Interfaces == Loose coupling!
When a module is initialized, it can register views and services or inject a view into a Shell region.
public voidInitialize()
{
_regionManager.Regions["MainRegion"].Add(newSimpleView());
}
This code finds a region in my shell called MainRegion and injects my view (UserControl) into it. This is a great pattern to use but currently it has no advantage over just using UserControl! What else can this baby do?
The big advantage in using PRISM here is how the modules are located (discovered) and loaded
- Static Module Loading
- Dynamic Module Loading
- Directory Driven Module Loading
protected override IModuleEnumerator GetModuleEnumerator()
{
return new DirectoryLookupModuleEnumerator(@".\Modules");
}
- Configuration Driven Module Loading
protected override IModuleEnumerator GetModuleEnumerator()
{
ConfigurationStore store = new ConfigurationStore();
return new ConfigurationModuleEnumerator(store);
}
The static module loading is similar to how you would do it only using UserControls but the real power is in the dynamic loading of modules. Currently there are 3 dynamic methods supported: Find all the modules in a directory, load from configuration file or load modules on demand!
If you found this article useful, please 
Read more