using StructureMap; using StructureMap.Pipeline; using Stylet; using System; using System.Collections.Generic; using System.Reflection; using System.Windows; namespace Bootstrappers { public class StructureMapBootstrapper : BootstrapperBase where TRootViewModel : class { private IContainer container; private object _rootViewModel; protected virtual object RootViewModel { get { return this._rootViewModel ?? (this._rootViewModel = this.GetInstance(typeof(TRootViewModel))); } } protected override void ConfigureBootstrapper() { this.container = new Container(config => { this.DefaultConfigureIoC(config); this.ConfigureIoC(config); }); } /// /// Carries out default configuration of the IoC container. Override if you don't want to do this /// protected virtual void DefaultConfigureIoC(ConfigurationExpression config) { var viewManagerConfig = new ViewManagerConfig() { ViewFactory = this.GetInstance, ViewAssemblies = new List() { this.GetType().Assembly } }; config.For().Add(new ViewManager(viewManagerConfig)); // Trick it into not taking ownership of (and disposing) the instance config.For().Add(c => this).LifecycleIs(); config.For().Add().LifecycleIs(); config.For().Add().LifecycleIs(); config.For().Add().LifecycleIs(); config.Scan(x => x.Assembly(this.GetType().Assembly)); } /// /// Override to add your own types to the IoC container. /// protected virtual void ConfigureIoC(ConfigurationExpression config) { } public override object GetInstance(Type type) { return this.container.GetInstance(type); } protected override void Launch() { base.DisplayRootView(this.RootViewModel); } public override void Dispose() { ScreenExtensions.TryDispose(this._rootViewModel); if (this.container != null) this.container.Dispose(); base.Dispose(); } } }