Wingedox

自己记录学习笔记的地方

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

 

新建类BankShellApplication继承自Microsoft.Practices.CompositeUI.WinForms空间下的FormShellApplication,
BankShellApplication类里包含程序入口Main():

public class BankShellApplication : FormShellApplication<WorkItem, BankShellForm>
 
{
  [STAThread]
  
public static void Main()
  
{
   
new BankShellApplication().Run();
  }

    

其中Run()在public abstract class CabApplication<TWorkItem>中定义:

        public void Run()
        
{
            RegisterUnhandledExceptionHandler();
            Builder builder 
= CreateBuilder();
            AddBuilderStrategies(builder);
            CreateRootWorkItem(builder);

            IVisualizer visualizer 
= CreateVisualizer();
            
if (visualizer != null)
                visualizer.Initialize(rootWorkItem, builder);

            AddRequiredServices();
            AddConfiguredServices();
            AddServices();
            AuthenticateUser();
            ProcessShellAssembly();
            rootWorkItem.BuildUp();
            LoadModules();
            rootWorkItem.FinishInitialization();

            rootWorkItem.Run();
            Start();

            rootWorkItem.Dispose();
            
if (visualizer != null)
                visualizer.Dispose();
        }

CabApplication和CabShellApplication的继承关系:


逐一看看Run()里做了哪些工作:

错误处理
RegisterUnhandledExceptionHandler();处理未经处理的意外错误,该函数种将程序域截获未处理的Exception交由OnUnhandledException ()处理,OnUnhandledException()是虚函数在BankShellApplication类中队该函数进行了重载:

        public override void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        
{
            Exception ex 
= e.ExceptionObject as Exception;

            
if (ex != null)
            
{
                MessageBox.Show(BuildExceptionString(ex));
            }

            
else
            
{
                MessageBox.Show(
"An Exception has occured, unable to get details");
            }


            Environment.Exit(
0);
        }


        
private string BuildExceptionString(Exception exception)
        
{
            
string errMessage = string.Empty;

            errMessage 
+= exception.Message + Environment.NewLine + exception.StackTrace;

            
while (exception.InnerException != null)
            
{
                errMessage 
+= BuildInnerExceptionString(exception.InnerException);
                exception 
= exception.InnerException;
            }


            
return errMessage;
        }


        
private string BuildInnerExceptionString(Exception innerException)
        
{
            
string errMessage = string.Empty;

            errMessage 
+= Environment.NewLine + " InnerException ";
            errMessage 
+= Environment.NewLine + innerException.Message + Environment.NewLine + innerException.StackTrace;

            
return errMessage;
        }

创建Builder并加载Strategy

在创建过程中在Builder中加载了必要的Strategy和Policy,这时的builder.Strategies中有4个Strategy3个Policy

再调用虚函数AddBuilderStrategies(),该函数在WindowsFormsApplication类中进行了重载,该重载在Builder中加载了WinFormServiceStrategy等三个Strategy。

builder.Strategies.AddNew<EventBrokerStrategy>(BuilderStage.Initialization); builder.Strategies.AddNew<CommandStrategy>(BuilderStage.Initialization); builder.Strategies.Add(new RootWorkItemInitializationStrategy(this.OnRootWorkItemInitialized), BuilderStage.Initialization); builder.Strategies.AddNew<ObjectBuiltNotificationStrategy>(BuilderStage.PostInitialization); builder.Policies.SetDefault<ISingletonPolicy>(new SingletonPolicy(true)); builder.Policies.SetDefault<IBuilderTracePolicy>(new BuilderTraceSourcePolicy(new TraceSource("Microsoft.Practices.ObjectBuilder"))); builder.Policies.SetDefault<ObjectBuiltNotificationPolicy>(new ObjectBuiltNotificationPolicy()); builder.Strategies.AddNew<WinFormServiceStrategy>(BuilderStage.Initialization); builder.Strategies.AddNew<ControlActivationStrategy>(BuilderStage.Initialization); builder.Strategies.AddNew<ControlSmartPartStrategy>(BuilderStage.Initialization);

创建并初始化RootWorkItem

RootWorkItem的类型是定义范型类BankShellApplication : FormShellApplication<WorkItem, BankShellForm>时指定的WorkItem;

        private void CreateRootWorkItem(Builder builder)
        
{
            rootWorkItem 
= new TWorkItem();
            rootWorkItem.InitializeRootWorkItem(builder);
        }

 new TWorkItem()时什么工作都没做,只是new了个新对象,这是WorkItem的构造函数

public WorkItem() { }

初始化WorkItem

  1. 将上面创建好的builder赋值给rootWorkItem,初始化locator;
  2. 将ObjectBuiltNotificationPolicy的代理和本地方法连接;
  3. 在Locator中加入自身;
  4. 将WorkItem的状态置为Inactive;
  5. 初始化几个集合:serviceCollection、commandCollection、workspaceCollection、workItemCollection、smartPartCollection、eventTopicCollection、uiExtensionSiteCollection;
  6. 新建WorkItem的Guid值。
        protected internal void InitializeRootWorkItem(Builder builder)
        
{
            
this.builder = builder;
            
this.locator = new Locator();

            InitializeFields();
            InitializeCollectionFacades();
            InitializeState();
        }


        private void InitializeFields()
        
{
            
if (builder == null)
                builder 
= parent.builder;

            
if (locator == null)
                locator 
= new Locator(parent.locator);

            
if (!locator.Contains(typeof(ILifetimeContainer), SearchMode.Local))
                locator.Add(
typeof(ILifetimeContainer), lifetime);
            //在前面已经加载
            ObjectBuiltNotificationPolicy policy 
= builder.Policies.Get<ObjectBuiltNotificationPolicy>(nullnull);

            
if (policy != null)
            
{
                policy.AddedDelegates[
this= new ObjectBuiltNotificationPolicy.ItemNotification(OnObjectAdded);
                policy.RemovedDelegates[
this= new ObjectBuiltNotificationPolicy.ItemNotification(OnObjectRemoved);
            }


            LocateWorkItem(
typeof(WorkItem));
            LocateWorkItem(GetType());

            status 
= WorkItemStatus.Inactive;
        }


        
private void LocateWorkItem(Type workItemType)
        
{
            DependencyResolutionLocatorKey key 
= new DependencyResolutionLocatorKey(workItemType, null);

            
if (!locator.Contains(key, SearchMode.Local))
                locator.Add(key, 
this);
        }


        
private void InitializeCollectionFacades()
        
{
            
if (serviceCollection == null)
            
{
                serviceCollection 
= new ServiceCollection(lifetime, locator, builder,
                    parent 
== null ? null : parent.serviceCollection);
            }


            
if (commandCollection == null)
            
{
                commandCollection 
= new ManagedObjectCollection<Command>(lifetime, locator, builder,
                    SearchMode.Up, CreateCommand, 
null, parent == null ? null : parent.commandCollection);
            }


            
if (workItemCollection == null)
            
{
                workItemCollection 
= new ManagedObjectCollection<WorkItem>(lifetime, locator, builder,
                    SearchMode.Local, 
nullnull, parent == null ? null : parent.workItemCollection);
            }


            
if (workspaceCollection == null)
            
{
                workspaceCollection 
= new ManagedObjectCollection<IWorkspace>(lifetime, locator, builder,
                    SearchMode.Up, 
nullnull, parent == null ? null : parent.workspaceCollection);
            }


            
if (itemsCollection == null)
            
{
                itemsCollection 
= new ManagedObjectCollection<object>(lifetime, locator, builder,
                    SearchMode.Local, 
nullnull, parent == null ? null : parent.itemsCollection);
            }


            
if (smartPartCollection == null)
            
{
                smartPartCollection 
= new ManagedObjectCollection<object>(lifetime, locator, builder,
                    SearchMode.Local, 
nulldelegate(object obj)
                        
{
                            
return obj.GetType().GetCustomAttributes(typeof(SmartPartAttribute), true).Length > 0;
                        }
,
                    parent 
== null ? null : parent.smartPartCollection);
            }


            
if (eventTopicCollection == null)
            
{
                
if (parent == null)
                    eventTopicCollection 
= new ManagedObjectCollection<EventTopic>(lifetime, locator, builder,
                        SearchMode.Local, CreateEventTopic, 
nullnull);
                
else
                    eventTopicCollection 
= RootWorkItem.eventTopicCollection;
            }


            
if (uiExtensionSiteCollection == null)
            
{
                
if (parent == null)
                    uiExtensionSiteCollection 
= new UIExtensionSiteCollection(this);
                
else
                    uiExtensionSiteCollection 
= new UIExtensionSiteCollection(parent.uiExtensionSiteCollection);
            }

        }


        
private void InitializeState()
        
{
            ID 
= Guid.NewGuid().ToString();
        }

    这几个集合都是ManagedObjectCollection,


    建立并初始化Visualizer

加载服务


    在RootWorkItem中加载必要的10个服务,如UIElementAdapterFactoryCatalog,这些服务在RootWorkItem.Services中

        private void AddRequiredServices()
        
{
            rootWorkItem.Services.AddNew
<TraceSourceCatalogService, ITraceSourceCatalogService>();
            rootWorkItem.Services.AddNew
<WorkItemExtensionService, IWorkItemExtensionService>();
            rootWorkItem.Services.AddNew
<WorkItemTypeCatalogService, IWorkItemTypeCatalogService>();
            rootWorkItem.Services.AddNew
<SimpleWorkItemActivationService, IWorkItemActivationService>();
            rootWorkItem.Services.AddNew
<WindowsPrincipalAuthenticationService, IAuthenticationService>();
            rootWorkItem.Services.AddNew
<ModuleLoaderService, IModuleLoaderService>();
            rootWorkItem.Services.AddNew
<FileCatalogModuleEnumerator, IModuleEnumerator>();
            rootWorkItem.Services.AddOnDemand
<DataProtectionCryptographyService, ICryptographyService>();
            rootWorkItem.Services.AddNew
<CommandAdapterMapService, ICommandAdapterMapService>();
            rootWorkItem.Services.AddNew
<UIElementAdapterFactoryCatalog, IUIElementAdapterFactoryCatalog>();
        }

AddConfiguredServices();加载配置文件中指定的Services;


AddServices();该函数是虚函数,在WindowsFormsApplication类中有重载,加载了一个ControlActivationService服务

protected override void AddServices() { RootWorkItem.Services.AddNew<ControlActivationService, IControlActivationService>(); }

AuthenticateUser();

 

装载Module


ProcessShellAssembly();

 装载可执行程序Shell中的Module,会调用IModule中的Load(),每个模块中都有个ModuleInit继承自IModule。

 

rootWorkItem.BuildUp()

 

将WorkItem的Parent属性赋值为Null;rootWorkItem.BuildUp():

        protected internal void BuildUp()
        
{
            
// We use Guid.NewGuid() to generate a dummy ID, so that the WorkItem buildup sequence can
            
// run (the WorkItem is already located with the null ID, which marks it as a service, so
            
// the SingletonStrategy would short circuit and not do the build-up).

            Type type 
= GetType();
            
string temporaryID = Guid.NewGuid().ToString();
            PropertySetterPolicy propPolicy 
= new PropertySetterPolicy();
            propPolicy.Properties.Add(
"Parent"new PropertySetterInfo("Parent"new ValueParameter(typeof(WorkItem), null)));

            PolicyList policies 
= new PolicyList();
            policies.Set
<ISingletonPolicy>(new SingletonPolicy(false), type, temporaryID);
            policies.Set
<IPropertySetterPolicy>(propPolicy, type, temporaryID);

            builder.BuildUp(locator, type, temporaryID, 
this, policies);
        }

在前面执行CabApplication.Run()时调用了CreateBuilder(),其中加载了RootWorkItemInitializationStrategy(this.OnRootWorkItemInitialized):

        private Builder CreateBuilder()
        
{
            Builder builder 
= new Builder();

            builder.Strategies.AddNew
<EventBrokerStrategy>(BuilderStage.Initialization);
            builder.Strategies.AddNew
<CommandStrategy>(BuilderStage.Initialization);
            builder.Strategies.Add(
new RootWorkItemInitializationStrategy(this.OnRootWorkItemInitialized), BuilderStage.Initialization);
            builder.Strategies.AddNew
<ObjectBuiltNotificationStrategy>(BuilderStage.PostInitialization);

            builder.Policies.SetDefault
<ISingletonPolicy>(new SingletonPolicy(true));
            builder.Policies.SetDefault
<IBuilderTracePolicy>(new BuilderTraceSourcePolicy(new TraceSource("Microsoft.Practices.ObjectBuilder")));
            builder.Policies.SetDefault
<ObjectBuiltNotificationPolicy>(new ObjectBuiltNotificationPolicy());

            
return builder;
        }

执行builder.BuildUp(locator, type, temporaryID, this, policiew)后会执行RootWorkItemInitializationStrategy策略,RootWorkItemInitializationStrategy策略执行时会回调OnRootWorkItemInitialized

        public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
        
{
            WorkItem wi 
= existing as WorkItem;

            
if (wi != null && wi.Parent == null)
                callback();

            
return base.BuildUp(context, typeToBuild, existing, idToBuild);
        }

 

OnRootWorkItemInitialized是虚函数,在CabShellApplication类中有重载:
        protected sealed override void OnRootWorkItemInitialized()
        
{
            BeforeShellCreated();
            shell 
= RootWorkItem.Items.AddNew<TShell>();
            AfterShellCreated();
        }

AfterShellCreated()在WindowsFormsApplication中有重载:

protected override void AfterShellCreated() { RegisterUIElementAdapterFactories(); RegisterCommandAdapters(); } private void RegisterCommandAdapters() { ICommandAdapterMapService mapService = RootWorkItem.Services.Get<ICommandAdapterMapService>(); mapService.Register(typeof(ToolStripItem), typeof(ToolStripItemCommandAdapter)); mapService.Register(typeof(Control), typeof(ControlCommandAdapter)); } private void RegisterUIElementAdapterFactories() { IUIElementAdapterFactoryCatalog catalog = RootWorkItem.Services.Get<IUIElementAdapterFactoryCatalog>(); catalog.RegisterFactory(new ToolStripUIAdapterFactory()); }

BeforeShellCreated()、AfterShellCreated()在BankShellApplication类中有重载:

        protected override void AfterShellCreated()
        
{
            
base.AfterShellCreated();

            ToolStripMenuItem fileItem 
= (ToolStripMenuItem)Shell.MainMenuStrip.Items["File"];

            RootWorkItem.UIExtensionSites.RegisterSite(UIExtensionConstants.MAINMENU, Shell.MainMenuStrip);
            RootWorkItem.UIExtensionSites.RegisterSite(UIExtensionConstants.MAINSTATUS, Shell.mainStatusStrip);
            RootWorkItem.UIExtensionSites.RegisterSite(UIExtensionConstants.FILE, fileItem);
            RootWorkItem.UIExtensionSites.RegisterSite(UIExtensionConstants.FILEDROPDOWN, fileItem.DropDownItems);

            
// Load the menu structure from App.config
            UIElementBuilder.LoadFromConfig(RootWorkItem);
        }

shell = RootWorkItem.Items.AddNew<TShell>(); 初始化Shell,Shell是在项目中新建的主窗体。在执行AddNew<TShell>时在策略ControlSmartPartStrategy中将递归查询TShell(继承自Form)中Controls下的所有控件,将打有SmartPartAttribute标签、继承自IWorkspace和ISmartPartPlaceholder的控件都添加到WorkItem.Items中,这样就可以用

IWorkspace workspace = workItem.Workspaces["Name"]的方式取得了,以下是 策略ControlSmartPartStrategy中部分代码:

private bool ShouldAddControlToWorkItem(WorkItem workItem, Control control) { return !workItem.Items.ContainsObject(control) && (IsSmartPart(control) || IsWorkspace(control) || IsPlaceholder(control)); } if (ShouldAddControlToWorkItem(workItem, control)) { if (control.Name.Length != 0) workItem.Items.Add(control, control.Name); else workItem.Items.Add(control); return true; }

LoadModules();装载初始化配置文件中的Module并执行Load().
rootWorkItem.FinishInitialization();初始化WorkItemExtension,触发WorkItem.Initialized事件;

rootWorkItem.Run();调用RootWorkItem的OnRunStarted(),这是个虚函数并触发WorkItem.RunStarted事件;


Start();虚函数,在FormShellApplication有重载启动Form开始程序。

protected override void Start() { Application.Run(Shell); }
posted on 2007-07-22 17:05  想飞的黄牛  阅读(605)  评论(0)    收藏  举报