Sunday, August 5, 2012

Prism Region Manager, Sevice Locator and Module


Some code to demo additional features of Prism
(1) ServiceLocator.GetInstance = Container.Resolve and inject
(2) Region Manager can define region for injecting UserControl (view)
(3) Module execute injection of view
(4) Adding Module to ModuleCatalog does injection of Region Manager

App run bootstrapper

   public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            OtherBootstrapper b = new OtherBootstrapper();
            b.Run(); 
        }
    }
Bootstrapper: Service Locator, ModuleCatalog

   public class OtherBootstrapper :  UnityBootstrapper
    {
        protected override void InitializeShell()
        {
            (Application.Current.MainWindow = (Window)Shell).Show();
        }

        protected override DependencyObject CreateShell()
        {
            //ServiceLocator replaced Container.Resolve
           return ServiceLocator.Current.GetInstance<ShellWin>();
          //  return Container.TryResolve<ShellWin>();         }

        protected override void ConfigureContainer()
        {
           // this will run default config such as EventAggregator, ServiceLocator and region manager
            base.ConfigureContainer();          
        }

        protected override void ConfigureModuleCatalog()
        {
            // amazingly, add ModuelInfo will do DI just like container.Resolve
            ModuleCatalog.AddModule(new ModuleInfo()
            {
                ModuleName = typeof(OtherFeatureModule).Name,
                ModuleType = typeof(OtherFeatureModule).AssemblyQualifiedName
            });
            base.ConfigureModuleCatalog();
        }
    }

   public class OtherFeatureModule : IModule
    {
        IRegionManager _mgr;
        // DI does happend when ModuleInfor Added to Catalog
        public OtherFeatureModule(IRegionManager mgr)
        {
            _mgr = mgr;
        }
        public void Initialize()
        {
            _mgr.Regions["mainReg"].Add(new uc1 ());
        }
    }

ShellWin.xaml  --- Region added to RegionManager.Region Collection
    xmlns:ps="http://www.codeplex.com/CompositeWPF"
    <Grid>
        <ContentControl ps:RegionManager.RegionName="mainReg" />
    </Grid>

1 comment:

Angshuman said...

Your blog is very useful.