15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

764 ❘ ChaPTer 28 mAnAGed extensibility frAmewOrk<br />

}<br />

}<br />

}<br />

ImportsSatisfied(this, new ImportEventArgs {<br />

StatusMessage = "ICalculator import successful" });<br />

code snippet WPFCalculator/CalculatorImport.cs<br />

The event of the CalculatorImport is connected to an event h<strong>and</strong>ler on creation of the CalculatorImport<br />

to write a message to a TextBlock for displaying status information:<br />

private void InitializeContainer()<br />

{<br />

var catalog = new DirectoryCatalog(<br />

Properties.Settings.Default.AddInDirectory);<br />

container = new CompositionContainer(catalog);<br />

calcImport = new CalculatorImport();<br />

calcImport.ImportsSatisfied += (sender, e) =><br />

{<br />

textStatus.Text += String.Format("{0}\n", e.StatusMessage);<br />

};<br />

container.ComposeParts(calcImport);<br />

}<br />

InitializeOperations();<br />

code snippet WPFCalculator/MainWindow.xaml.cs<br />

lazy loading of Parts<br />

By default, parts are loaded from the container, for example, by calling the extension method<br />

ComposeParts() on the CompositionContainer. With the help of the Lazy class, the parts can<br />

be loaded on first access. The type Lazy allows the late instantiation of any type T <strong>and</strong> defines the<br />

properties IsValueCreated <strong>and</strong> Value. IsValueCreated is a Boolean that returns the information if the<br />

contained type T is already instantiated. Value initializes the contained type T on first access <strong>and</strong> returns<br />

the instance.<br />

The import of an add-in can be declared to be of type Lazy, as shown in the Lazy<br />

example.<br />

[Import(typeof(ICalculator))]<br />

public Lazy Calculator { get; set; }<br />

code snippet WPFCalculator/CalculatorImport.cs<br />

Calling the imported property also requires some changes to access the Value property of the Lazy<br />

type. calcImport is a variable of type CalculatorImport. The Calculator property returns<br />

Lazy. The Value property instantiates the imported type lazily <strong>and</strong> returns the<br />

ICalculator interface, where now the GetOperations() method can be invoked to get all supported<br />

operations from the calculator add-in.<br />

private void InitializeOperations()<br />

{<br />

Contract.Requires(calcImport != null);<br />

Contract.Requires(calcImport.Calculator != null);<br />

var operators = calcImport.Calculator.Value.GetOperations();<br />

foreach (var op in operators)<br />

{<br />

var b = new Button();<br />

b.Width = 40;<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!