Prism Study Notes

Source: Internet
Author: User

I 've been busy studying prism in the last three weeks, leaving some study notes... and finally found that I still have to read the official guide carefully. This is a good way to learn.

 

Key Aspect 1:

In Cal, a module is a class that implements the imodule interface. This interface contains only one method called initializae. If you regard the Bootstrap program as the main method of the application, the initialize method is the main method of each module.

Key Aspect 2:

The functions of _ contianer and _ regionmanager mentioned in the initialize method in the module should be discussed. If the interfaces do not define them, where do they come from? Do we need to hard-code the logic into the module to find these dependencies? Fortunately, the answer to the next question is "no". In this case, the IOC container comes in handy. When this module is loaded, it is parsed from the container and all specified dependencies are injected into the module's constructor container.

By allowing the module to directly access the container, the module can register and parse dependencies in the container in a mandatory way.

Key Aspect 2:

Cal (compoise application library) contains a region class. In general, this class is a handle covering these locations. The region class contains the views attribute, which is a read-only set of views displayed in a region. The view is added to the region by calling the add method of the region. The views attribute actually contains the generic set of objects. It is not limited to only including uielement. This set implements inotifypropertycollectionchanged so that the uielement associated with the same region can be bound with it and observe its changes.

Key Aspect 3:
Why is the views set of the region class weak type rather than the uielement type. Since WPF supports a wide range of templates, you can add models directly to a region. Then, an associated ememplate will be defined for the model, which will define the rendering mode of the model. If the added project is a uielement or user control, WPF will render it as is. This means that you only need to add the corresponding model and define a custom plate emplate to control the display, instead of creating a custom oderview control.

Key 4: Two registration methods for a region:

The first is to annotate the uielement in XAML by using the regionname of the additional attribute. For example, the XAML that defines maintoolbarregion is as follows:

<Itemscontrol grid. Row = "1" grid. Column = "1"

X: Name = "maintoolbar"

CAL: regionmanager. regionname = "maintoolbarregion">

<Itemscontrol. itemspanel>

<Itemspaneltemplate>

<Wrappanel/>

</Itemspaneltemplate>

</Itemscontrol. itemspanel>

</Itemscontrol>

After a region is defined through XAML, regionmanager is automatically registered at runtime, which is a compliant service registered by the pilot program. Regionmanager is essentially a dictionary, where the keyword is the name of the region and the value is an instance of the iregion interface. Note: If the additional attributes do not work, or you need to dynamically register other regions, You can manually create an instance of the region class or derived class, and add it to the regionmanager's regions collection.

The second method is createregion, which returns a new allactiveregion instance. A region can contain active or inactive views. For itemscontrol, all its projects are always active because it has no sense of choice. However, for regions of other types (such as selector), only one item is selected at a time. View can implement the iactiveaware interface, so that you can get the selected notification from other regions. If a view is selected, it sets its isselected attribute to true.

Key Aspect 5:

The implementation of the adapter depends entirely on the type of the uielement it applies.

Key Aspect 6:

During Composite Application Development, you may have to create some additional area adapters and areas. For example, you need an adapter to adapt to the controls provided by third-party vendors. To register a new region adapter, you must overwrite the confingureregionadatermappins method in the Bootstrap program.

Key Aspect 7: Local Region

By default, there is only one regionmanager instance in the application, so that the scope of each region is global. Sometimes you may want each view to have its own region like a shell. Cal allows you to define a local regionmanager for a view, so that any region defined in the view or its subviews will be automatically registered in the local region.

Key Aspect 8:

Elements in WPF can be bound to commands to process execution logic and enable or disable elements. When a uielement is bound to a command, if the canexecute attribute of the command is false, it is automatically disabled. In XAML, commands can be bound through declaration. In WPF, routeduicommand is provided by default.

Key Aspect 9:

Cal includes many new commands (such as delegatecommand <t>, which allows you to specify two delegates for the execute and canexecute methods in the constructor ). With this command, you do not have to delegate to each view by defining the view, or create your own commands for each operation.

Key Aspect 10:

Cal includes the compositewpfevent <tpayload> class, which inherits the eventbase class and provides specific support for WPF. This class uses the delegate rather than the website's. Net event class to execute Publishing. Essentially, it uses the default delegate delegatereference class (for more information about weak delegates, see msdn.microsoft.com/library/ms408247 ). This will allow garbage collection of subscribers, and they will not be shown to cancel the subscription in a timely manner.

 

 

Silverlight about PRISM

Key Aspect 1:

Specify a ref value in moudleinfo. The ref value contains the module's. xap file path, in the specified. when the xap file is used, the pilot program knows that the Assembly is unavailable, so it is forwarded to the server for asynchronous retrieval. xap file. After the. xap file is loaded, Prism loads the Assembly, creates the module type, and initializes the module.

For. xap files that contain multiple modules, you can create a moudlegroup to contain a group of moudleinfo objects, and set the moudlegroup ref to load the modules from a single. xap file.

When creating the Silverlight module to be included in the. xap file, you must create a Silverlight application (instead of a Silverlight library ). Then, you need to reference all the module projects to be placed in the. xap file. You need to delete the app. XAML file and page. XAML file because the. xap file will not be loaded or run as the typical. xap file. The. xapfile is only a container (.zip file ).

Key Aspect 2:

Cal allows you to directly define a region in XAML by using an additional attribute for the regionmanager class. With this attribute, you can specify a region in shell and then specify the view to be hosted in the region. The regionname attribute can be applied to itemscontrol and its derived controls (such as ListBox), selector and its derived controls (such as tabcontrol), and contentcontrol and its derived controls (such as scrollviewer control ).

Key Aspect 3:

If you want to use the mvvm mode to define a view, you can mix the region and service location of the container. The view and view model are independent of each other, so that the module can add the view and view model at runtime. For example, if you change gamelistmoudle, you can register the view and view model with the container, and then add the view and view model before applying the view to the region. As follows:

public class GameListModule : IModule{     IRegionManager regionManager = null;     IUnityContainer container = null;     public GameListModule(IUnityContainer con, IRegionManager mgr)     {      regionManager = mgr;      container = con;   }     public void Initialize()     {          RegisterServices();         // Build the View        var view = container.Resolve<IGameListView>();        // Get an Implemenation of IViewModel      var viewModel = container.Resolve<IGameListViewModel>();    // Marry Them      view.ApplyModel(viewModel);    // Show it in the region    regionManager.AddToRegion("LookupRegion", view);  }  void RegisterServices()  {     container.RegisterType<IGameListView, GameListView>();     container.RegisterType<IGameListViewModel, GameListViewModel>();  }}

By using this method, you can use the UI compound and keep the strict separation of mvvm.

Key Aspect 4:

When multiple views are used in an application through UI combination, a common problem occurs. Even if you have built an independent view to support better testing and opening, there are usually some touchpoints that make the view unable to be fully isolated. Because communication is required, these touchpoints are logically coupled. No matter how coupled these touchpoints are logically, you still want the view to be as loosely coupled as possible.

To implement loose coupling and cross-view communication, Cal supports a service called "event aggregation". With this event aggregation, global event publishers and users can access different parts of the Code. This type of access provides a non-tightly coupled direct communication method, which can be completed using the Cal ieventaggregator interface. This event can be used to publish and subscribe to events across different modules of the application.

Before communication, you need to create a simple event derived from the compositepresentationevent <t> class. You can use this generic type to specify the load of the event to be published. After defining an event, event aggregation can call its getevent method to publish the event. This searches for a single event to be aggregated. The first event aggregator that calls this method and creates a single instance can call the publish method to create an event from this event. As a subscriber, you can also specify the filter called under specific circumstances.

Key Aspect 5:

In Silverlight (unlike WPF), there is no real command infrastructure. Cal supports a class to help solve this problem: delegatecommand (before Silverlight does not support this function ). To bind this command to XAML, use the click. Command additional attribute in the Microsoft. Practices. Composite. Presentation. commands namespace. Then bind the value of this command to the command in viewmode.

Key Aspect 6:

Dependencies can be added to the project during object construction. This is also the working principle of dependency injection. The container task is to create a processing type. Through the container, you can register the type and parse the registered type.

For example, assume that there is an idataacess interface of a specific type. When starting an application, you can instruct the container to register the type and require any other location of the type in the application, can require the container to parse this type.

In addition, the container can also process dependency structure injection. If an object to be created by the container constructor accepts the interface that can be parsed by the container, the container parses the type and passes it to the constructor.

Key Aspect 7:

When registering a type with a container, it also instructs the container to handle the lifetime of this type in a special way. For example, if you want to process the logging component, you may want to treat it as a single component, so that each application component that requires logging won't obtain a copy (this is the default action ). Therefore, you can implement the abstract class of lifetimemanager.

Multiple lifecycle managers are supported:

Containercontrolledlifetimemanager is a single instance by process, while perthreadlifetimemanager is a single instance by thread. For externallycontrolledlifetimemanager, containers have weak references to this single instance. If the object is released externally, the container creates a new instance. Otherwise, the system returns the activity object contained in the weak reference.

Key Aspect 8: Command of prism

The P & P team also saw many restrictions on WPF command, especially coupling with UI elements and unsupported command combinations. Therefore, they added another set of commands in Prism: delegatecommand and compositecommand.

Delegatecommand: implements the icommand interface of WPF and supports only one canexecute and execute hook. However, it implements an interface called iactiveaware to indicate whether the interface is in the set state, non-active delegatecommand is never executed.

Compositecommand: it is also an implementation of the icommand interface of WPF, but it is also a combination of delegatecommand, which can be registered or canceled to register delegatecommand, when all built-in delegatecommands in the active state can be executed, canexecute returns true. When the compositecommand is executed, the internal delegatecommand is executed in sequence (if executable)

The syntax of delegatecommand and compositecommand is skipped here.

In addition, delegatecommand and compositecommand are not a substitute for routecommand, but a powerful supplement. The routecommand Routing Mechanism frees us from worrying about the current user focus. Besides, the dozens of commonly used commands built in WPF save us a lot of development time.

 

The following 6 Q & A from http://msdn.microsoft.com/zh-cn/subscriptions/dd365973.aspx

1.Why use dependency injection containers?

We know that in Composite Application, modules are loosely coupled, that is, the dependencies between modules are reduced as much as possible during design. However, from a business perspective, they always need to communicate and cooperate with each other. Therefore, the dependency injection container plays a bridge-like role here. For example, when a component instance is created, it depends on another component or service. In this case, the dependency injection container will inject the required information into it, the injection method avoids coupling between direct references. in addition, using dependency injection containers has the following benefits:

Components do not have to locate their dependencies and maintain their lifecycles. Replacing the dependencies does not affect the component code, therefore, components become easier to test.

Because the new services required by the system are easily added to the container, the system maintenance difficulty is also reduced.

2. PrismDependency injection container

Open the source code of the Composite Application Library (CAL). Instead of finding a dependency injection container implementation, we found a dependency injection container appearance interface icontainerfacade, it uses the appearance mode to abstract the most basic function "resolution" (RESOLVE) of a dependency injection container ).

In fact, the patterns & Practices Team designed to make prism compatible with more dependency injection containers (such as spring. net, Castle Windsor, unity, and so on). Therefore, the icontainerfacade interface is used in the prism source code instead of a specific container.

However, by default, Prism uses a lightweight and scalable dependency injection container in another open-source project "Unity" as the default container unitycontainer. the container implements three injection methods: constructor injection, property injection, and method injection.

3.Performance overhead of dependency injection containers

Because the underlying mechanism of registering a type to a dependency injection container and then using the container to parse (RESOLVE) A type instance object is "reflection", the overhead is relatively large, if you need to frequently create a large number of instances, whether to use the dependency injection container requires careful consideration. A large number of dependencies and deep dependency nesting can also cause performance problems. in addition, if a component is neither dependent on other components or services nor dependent on other components, it is unwise to put it into the dependency injection container.

4.Whether to register as a singleton

When registering a default type ing or registering an instance with the dependency injection container, we have a question: whether to register in singleton mode. if yes, the objects parsed in the container every time are the same object instance; otherwise, the new instance is created every time. generally, for some global services and shared statuses, We will register them as the singleton mode, for those dependencies that require a new instance to be injected each time, we will register them in non-singleton mode.

5.UseIunitycontainerOrIcontainerfacade

They are located in Microsoft. practices. composite and Microsoft. practices. in the unity namespace, although they can all be used as high-level interfaces of containers, using iunitycontainer basically means to directly use the unity container (the dependency injection container in the Unity project ), the use of icontainerfacade means that you can be compatible with various containers. however, we know that icontainerfacade basically only provides one function "resolution", but in terms of a basic dependency injection container, it is often not just this function, for example, at least type registration and instance registration are required. Therefore, iunitycontainer is recommended in most cases. We can see this from the open source project stocktraderri, unless it is one of the following situations:

  • L as an isV (independent software vendor, independent software vendor), you write some services that provide multi-container support.
  • L your service is used in a multi-container system

(The new container MEF (managed extensibility framework) is available in the latest version 4.1)

6.Code ConfigurationOrConfiguration file configuration

To address this issue, I will refer to Martin Fowler's article for some reference:

"Another issue of code configuration vs. configuration files is relatively independent, but it is often associated with other issues: how to configure service assembly, through the configuration file or directly code assembly? For most applications that need to be deployed in multiple places, a separate configuration file is more suitable. Configuration files are almost all XML files, and XML is indeed suitable for this purpose. However, sometimes it is easier to implement the Assembly directly in the program code. For example, a simple application does not have many deployment changes. Therefore, it is much clearer to use a few pieces of code for configuration than to use XML files.

In contrast, sometimes application assembly is very complex and involves a large number of conditional steps. Once the configuration logic in the programming language becomes complex, you should describe the configuration information in a proper language to make the program logic clearer. Then, you can write a constructor (builder) class to complete the assembly. If there are more than one constructor scenario, you can provide multiple constructor classes and select between them through a simple configuration file.

I often find that people are too eager to define configuration files. Programming Languages usually provide simple and powerful configuration management mechanisms. Modern programming languages can also compile programs into small modules and insert them into large systems. If the compilation process is laborious, the script language can also help. Generally, configuration files should not be written in programming languages because they must be edited by system administrators who do not understand programming. However, what is the probability of such a situation? Do we really want programmers who do not know how to change the transaction isolation level of a complex server-side application? Only when it is very simple can non-Programming Language configuration files have the best effect. If the configuration information becomes complex, you should select a proper programming language to compile the configuration file ".

 

Problems encountered by Prism (comprise Application Guidance for WPF:

Problem 1: Resolve Type Mismatch occurs when the startup class unitybootstrapper is rewritten.

Description: After a namespace is added:

Using Microsoft. Practices. Prism. modularity;

Using Microsoft. Practices. Prism. unityextensions;

Later (no exception) in rewriting protected override dependencyobject createshell ()

Encountered:

The reslove function type does not match. Add the namespace as follows:

Using Microsoft. Practices. Unity.
Cause: the overloaded version of the function is defined under the namespace.

(Not completed... To be continued ....)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.