Microsoft Cloud Authors: Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Dependency Injection and Microsoft Windows Forms

A walkthrough using Microsoft's Composite UI Application Block

The patterns & practices group at Microsoft provides architectural and design guidance for users of Microsoft technologies. Part of the way they do this is by producing and distributing packages called "application blocks." An application block consists of a functional subsystem or software framework that can be valuable in several ways. Application blocks can be implemented in many types of applications as time-saving subsystems. They are also reference examples of software designed and developed using the best practices of Microsoft architecture. Application blocks are freely distributed with all source code and documentation.

The Composite User Interface Application Block
The Composite UI Application Block (called "CAB" in the online community) is the first application block that has been developed exclusively for .NET 2.0. It is an architectural framework that is designed to help developers quickly implement loosely coupled Windows Forms applications. It employs a number of industry standard design patterns, including Model/View/Controller, Inversion of Control/Dependency Injection, and Publish/Subscribe.

Dependency Injection is a design pattern that was originally developed in the Java community. The basic idea of Dependency Injection is to design software that consists of a number of highly cohesive modules that have predefined interfaces, and to determine the details of how the objects interact with one another at run time. A great in-depth article on Dependency Injection by Martin Fowler can be found at www.martinfowler.com/articles/injection.html.

The goal of this article is to provide a straightforward introduction to CAB that focuses on its implementation of Dependency Injection. It will do this by providing step-by-step instructions for the construction of a simple Windows Forms application.

The demo application that will be built is a very simple master/detail data viewer. The interface will consist of two list boxes. The list box on the left side of the form will display a set of categories. Clicking on one of the items in this list box will cause line items in that category to be displayed in the list box on the right. The sample data we will use will be a set of shopping lists stored in an XML file.

CAB Installation and Prerequisites
The CAB installation package can be downloaded from the Microsoft patterns & practices Web site. In order to install CAB, you must have the .NET 2.0 Framework installed on the development machine. This walkthrough assumes that you will be using Visual Studio 2005 and C# for development.

Create the Shell Application
Open Visual Studio 2005 and create a new project of type "Windows Application." Name the project "DataViewerShell" and change the name of the solution to "ListManager."

Before starting to code we need to bring the CAB assemblies into the solution. You can add references to the compiled assemblies directly, if you have already built CAB, or you can just include the projects in your solution. The CAB assemblies that are used for this walkthrough are: "CompositeUI," "CompositeUI.Utility," "CompositeUI.WinForms," and "ObjectBuilder."

After you have included the CAB assemblies, the first step is to create the shell form. Right-click on the project and add a new Windows Form. Name it "ShellForm.cs." To fulfill the requirements of our sample application, we will need two list boxes to show up on this form: one for the master data on the left and one for the details on the right. Using CAB however, the only thing we will do in the shell is to create placeholders (called "Workspaces") where the controls will reside.

A workspace is a type of control that is included in CAB. If you want to use the designer to add workspaces to the shell form, you may want to load them into the toolbox. Bring up the toolbox if it is hidden or closed, scroll to the bottom, right-click in the "General" section, and select "Choose Items." In the "Choose Toolbox Items" dialog, click on "Browse" and navigate to the location of the "Microsoft.Practices.CompositeUI.WinForms.dll" assembly. Click on this assembly and click "OK," and the CAB workspace controls should load up into your toolbox.

For this example, the type of Workspace we will use will be a DeckWorkspace. This type allows stacking of multiple controls in the same place, like a deck of cards, only displaying the one on top. Drag two DeckWorkspace controls onto the shell form and arrange them as shown in Figure 1. Name the workspace on the left "navigationWorkspace," and the one on the right "viewerWorkspace."

The only actual coding we need to do in the shell is to create the application itself. Add a new class to the project and name it "ShellApplication.cs." This class will define the application object that launches and hosts the shell form. The only thing you need to do to wire this application up for CAB is to have it inherit from "Microsoft.Practices.CompositeUI.WinForms.FormShellApplicaiton<TWorkItem, TShell>."

The type declaration for FormShellApplication<TWorkItem, TShell> takes in two types. TWorkItem is the type of the default WorkItem, which is a basic container class in CAB. The default WorkItem for this shell doesn't need to have any special code in it, as it just acts as an overall container, so we can pass the type "WorkItem," which is the base class. TShell represents the type of the shell form. For TShell, we will specify the type of the shell form that we just created, "ShellForm."

The final step is to add the default static void Main() method to launch an instance of the application. Listing 1 shows the code for the complete ShellApplication class. The base FormShellApplication class does all of the work for us upon initialization: it creates an instance of the default work item and launches an instance of the ShellForm.

The application should build and run at this point. Check in the properties of DataViewerShell that the output type is "Windows Application," then compile and launch the application in the debugger. You should see a blank ShellForm like the one shown in Figure 2.

Create the First Module
CAB provides base container classes called "Modules," which represent sets of related controls and functionality. Using Dependency Injection, modules can be plugged into a shell at run time. CAB user controls are called "SmartParts," since they are context-aware controls that participate in Dependency Injection. The first module we will create for the demo application will be the one that will house the ListBox on the left side of our shell.

Add a new project of type "Class Library" to your solution and name it "ListOrganizerModule." Add references to the four CAB assemblies, but not to the shell application project. The List Organizer module needs three classes in it; one for the user control that holds the ListBox, a WorkItem class to act as a container for injection into the shell, and a class that inherits from the ModuleInit class to house initialization code for the module.

First, create a new User Control and name it "ListOrganizerListBox." In the Visual Studio Designer, drag a ListBox control onto the user control and name it "listBoxLists." This user control will be inserted into the navigationWorkspace on the shell form. Resize the control so that it is approximately the size of the navigationWorkspace.

Next, create the WorkItem. Add a new class to the project, and name it "ListOrganizerWorkItem." Modify the class declaration so that it inherits from Microsoft.Practices.CompositeUI.WorkItem. All we need to do in this class is to write an overload of the "Run" method that takes in the workspace where we want the control to show up. The code for this is shown in Listing 2.

The overload of the "Run" method takes in a parameter of type IWorkspace. It calls the "Show" method on the IWorkspace, passing in a new instance of the ListOrganizerListBox user control. The new instance is created by calling the AddNew<TType> generic factory method on the WorkItem's "Items" property. This method creates an instance of the specified type, injects it into the WorkItem, and returns a reference to it.

Finally, we need to create the ModuleInit class (see Listing 3). This class is the default implementation of IModule, which is the interface that defines a module. Add a new class to the project and name it "ListOrganizerInit.cs." Modify the class declaration so that it inherits from Microsoft.Practices.CompositeUI.ModuleInit.

Add a private member and public property for the parent work item. Mark the property with the "ServiceDependency" attribute - doing this will cause CAB to automatically initialize the value when the application starts.

Override the Load method of the ModuleInit class to load our module into the shell. This override does three things. First, it calls the Load method on the base class. Second, it creates an instance of the ListOrganizerWorkItem class using the generic factory method on the parent work item's collection of work items. Finally, it calls the overload of "Run" on the ListOrganizerWorkItem that we created in that class, which loads our user control into the correct workspace on the shell form.

More Stories By Guy Starbuck

Guy Starbuck is a senior application architect for Stericycle, Inc. He has been working in the software industry for over nine years. Guy lives in Arlington Heights, IL with his wife and son.

Comments (6)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in development and launches of disruptive technologies to create new market opportunities as well as enhance enterprise product portfolios with emerging technologies. His most recent venture was Octoblu, a cross-protocol Internet of Things (IoT) mesh network platform, acquired by Citrix. Prior to co-founding Octoblu, Chris was founder of Nodester, an open-source Node.JS PaaS which was acquired by AppFog and ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...