<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C# It !</title>
	<atom:link href="http://www.csharpit.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.csharpit.com</link>
	<description>Miky Petrescu Blog</description>
	<lastBuildDate>Fri, 01 Jul 2011 21:58:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Composable Application – Lazy Loading with MEF</title>
		<link>http://www.csharpit.com/?p=39</link>
		<comments>http://www.csharpit.com/?p=39#comments</comments>
		<pubDate>Mon, 21 Feb 2011 17:25:00 +0000</pubDate>
		<dc:creator>Miky</dc:creator>
				<category><![CDATA[WPF/Silverlight]]></category>

		<guid isPermaLink="false">http://www.csharpit.com/?p=39</guid>
		<description><![CDATA[Today I would like to talk about lazy loading of application parts. When we use the [Import] or [ImportMany] attributes...]]></description>
			<content:encoded><![CDATA[<p>Today I would like to talk about lazy loading of application parts.</p>
<p>When we use the [Import] or [ImportMany] attributes we are telling MEF to fill our variable with an <strong>instance</strong> of our desired type. This approach is great if we are dealing with small types, or we are certain that we need this instance, but what if the type we want to import is quite heavy and it would be a waste to load it right on the start? What if we want to import the types based on some user settings or a plug-in system?<br />
The solution for this is using Lazy<T> !</p>
<p>Lazy<T> &#8211; &#8220;Is wrapper class that provides lazy initialization semantics for any class library or user-defined type.&#8221; (<a href="http://msdn.microsoft.com/en-us/library/dd997286.aspx">MSDN</a>)<br />
The Lazy<T> class will instantiate the T type when we read its Value property or call its ToString() method.</p>
<p>MEF knows to work with Lazy<T> out of the box, and it&#8217;s pretty easy to do so.<br />
If we will continue <a href="http://www.csharpit.com/?p=11">my previous post</a>, instead of importing this way:</p>
<pre class="brush: csharp; title: ;">
[ImportMany(typeof(IModule))]
private List&lt;IModule&gt; _modules;
</pre>
<p>We would do something like that:</p>
<pre class="brush: csharp; title: ;">
[ImportMany(typeof(IModule))]
private List&lt;Lazy&lt;IModule&gt;&gt; _modules;
</pre>
<p>This way, when the OnImportsSatisfied method is called, our _modules variable will be filled with Lazy<IModule><br />
In order for us to instantiate a module we will have to read the Value property like that:</p>
<pre class="brush: csharp; title: ;">IModule firstModule=_Modules[0].Value; //Only now our imported module will be instantiated. Since we read its Value property</pre>
<p><strong>But here comes the question: <em>&#8220;How would you know which module to load?&#8221;</em></strong><br />
In order to identify the modules I &#8220;lazy imported&#8221;, we will have to provide a metadata to each exported type using the [ExportMetadata] attribute.</p>
<pre class="brush: csharp; title: ;">
[Export(typeof(IModule))]
[ExportMetadata(&quot;Name&quot;, &quot;Gui Designer&quot;)]
[ExportMetadata(&quot;RequiresAdmin&quot;, true)] //Just to demonstrate you can use any type in the metadata
public class GuiDesignerViewModel : IModule
……</pre>
<p>Ok, so now that we have some metadata in our exported types we will have to define an interface for it. (its usage will be explained bellow)</p>
<pre class="brush: csharp; title: ;">
public interface IModuleMetadata
{
    string Name { get; }
    bool RequiresAdmin { get; }
}
</pre>
<p>And change our lazy import definition to include the metadata.</p>
<pre class="brush: csharp; title: ;">
[ImportMany(typeof(IModule))]
private List&lt;Lazy&lt;IModule, IModuleMetadata&gt;&gt; _modules;
</pre>
<p>That&#8217;s it !<br />
MEF will automatically fill our <em>IModuleMetadata </em>with the values we set with <em>ExportMetadata</em>, without instantiating the type itself.</p>
<p>In order for us to check which module we want to load, we can check the lazy metadata.</p>
<pre class="brush: csharp; title: ;">
public void OnImportsSatisfied()
  {
        foreach (Lazy&lt;IModule, IModuleMetadata&gt; module in _modules)
        {
                if(module.Metadata.RequiresAdmin==false)
                {
                    Debug.WriteLine(&quot;Module loaded: &quot; + module.Metadata.Name);
                    _loadedModules.Add(module.Value); //Will create an instance
                }
            }
  }</pre>
<p>Or we can instantiate it when we actually need it!</p>
<pre class="brush: csharp; title: ;">
private void ShowModuleExecuted()
        {
            WindowManager windowManager = new WindowManager();
            Lazy&lt;IModule, IModuleMetadata&gt; selectedModule = _selectedModule;
            IModule moduleToLoad = selectedModule.Value; //Only now we instantiate the module
            windowManager.Show(moduleToLoad);
        }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.csharpit.com/?feed=rss2&#038;p=39</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Composable Application &#8211; Using MEF and Caliburn Micro</title>
		<link>http://www.csharpit.com/?p=11</link>
		<comments>http://www.csharpit.com/?p=11#comments</comments>
		<pubDate>Fri, 31 Dec 2010 13:43:04 +0000</pubDate>
		<dc:creator>Miky</dc:creator>
				<category><![CDATA[WPF/Silverlight]]></category>

		<guid isPermaLink="false">http://www.csharpit.com/?p=11</guid>
		<description><![CDATA[Introduction Caliburn Micro is a micro-framework for WPF, Silverlight and WP7 giving us great features for developing all sort of...]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p><a href="http://caliburnmicro.codeplex.com" target="_blank">Caliburn Micro</a> is a micro-framework for WPF, Silverlight and WP7 giving us great features for developing all sort of MVVM based application. Either you are developing a simple app or a complex one with composable module parts like Outlook, you will find CM to be fastest way to develop it, while keeping a true MVVM architecture.</p>
<p><strong>Modularity and Dependency Injection</strong><br />
When we develop an application which consist of multiple modules, we need to keep each module as an Independent block. Let’s take “Visual Studio” for example.  In Visual Studio you have a C# document editor, GUI designer, Resource designer etc.  We can think of each of them as module that Visual Studio is loading when needed. Such modules can be added, removed or replaced by a new version without recompiling the whole application. It’s sort of a plug-n-play system, or a Lego blocks if you want.</p>
<p>We achieve this functionality using <a href="http://mef.codeplex.com" target="_blank">MEF (Managed Extensibility Framework)</a>.<br />
But here’s a few important definitions when dealing with composable application:<br />
<strong>Bootstarpper </strong>- The object which initialize a composable application.<br />
<strong>Container </strong>– Keeps a collection of all modules and parts.</p>
<p>For our sample project I defined a simple interface in a separate project, which contains all interfaces. This way we keep a separation between the application and it’s modules:</p>
<pre class="brush: csharp; title: ;">
public interface IModule
{
    string DisplayName { get; }
}
</pre>
<p>Each module I make will have to implement this interface and <strong>export</strong> it, so the bootstrapper will find it as a composable part and add it to the container.</p>
<pre class="brush: csharp; title: ;">
[Export(typeof(IModule))]
public class DocumentEditorViewModel : IModule
{
	public string DisplayName
	{
		get { return &quot;My Document Editor&quot;; }
	}
}
</pre>
<p>This document editor class is defined in a separate project, and has a reference ONLY to the interfaces project.</p>
<p>On my main application I can import all modules easily like that :</p>
<pre class="brush: csharp; title: ;">
public class ShellViewModel : IShell ,IPartImportsSatisfiedNotification
{
        [ImportMany(typeof(IModule))]
        private IEnumerable&lt;IModule&gt; _modules;

        public ShellViewModel()
        {

        }
        #region IPartImportsSatisfiedNotification Members
        public void OnImportsSatisfied()
        {
		//executes when MEF finished loading my modules
        }
        #endregion
}
</pre>
<p><em>[ImportMany(typeof(IModule))]</em> attribute tells MEF to fill all Exported <em>IModule </em>objects, and construct them. You should not relay on the MEF to fill it on constructor, instead you implement the <em>IPartImportsSatisfiedNotification</em>. This way MEF will call the <em>OnImportsSatisfied </em>method when it finished loading all imports.<br />
(For importing on constructor, check for <em>[ImportingConstructor]</em> attribute.)</p>
<p><strong>Projects Dependencies</strong><br />
<a href="../wp-content/uploads/2010/12/composable-app-diagram.jpg"><img title="composable-app-diagram" src="../wp-content/uploads/2010/12/composable-app-diagram.jpg" alt="" width="510" height="126" /></a></p>
<p><strong>View Injection<br />
</strong>Caliburn Micro helps us keeping a separation between the View and the ViewModels by automatically finding the right View (either a UserControl or Window) for the viewmodel.<br />
For example, in the above example we had a DocumentEditorViewModel which was loaded dynamically using MEF as a IModule, Now I’ll create a new WPF window and name it DocumentEditorView and use Caliburn Micro “WindowManager” to display it like that:</p>
<pre class="brush: csharp; title: ;">
private void ShowModuleExecuted()
{
	WindowManager windowManager = new WindowManager();
	windowManager.Show(_selectedModule); //_selectedModule is set from the list of modules
}
</pre>
<p>If for example the _selectedModule object is DocumentEditorViewModel, WindowManager will look for a Window/UserControl type named DocumentEditorView, instantiate, display it and set _selectedModule as its DataContext! all that in a couple of simple lines.<br />
Caliburn is using name convention for finding the proper View, but it’s not a must. You can simply implement IViewAware in the ViewModel and pass the View manually.</p>
<p>This is just a drop in the ocean of Caliburn Micro and MEF, and I will extend this subject and sample in upcoming posts.</p>
<p><a rel="lightbox-imagesetname" href="http://www.csharpit.com/wp-content/uploads/2010/12/Project-Files.jpg"><img class="alignnone size-thumbnail wp-image-26" title="Project-Files" src="http://www.csharpit.com/wp-content/uploads/2010/12/Project-Files-150x150.jpg" alt="" width="150" height="150" /></a><a rel="lightbox-imagesetname" href="http://www.csharpit.com/wp-content/uploads/2010/12/Module-Loader.jpg"><img class="alignnone size-thumbnail wp-image-25" title="Module-Loader" src="http://www.csharpit.com/wp-content/uploads/2010/12/Module-Loader-150x150.jpg" alt="" width="150" height="150" /></a></p>
<p>Just one last thing..<br />
I&#8217;ll be very happy to answer any question you got and appreciate any comment on my first blog post ! <img src='http://www.csharpit.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Miky.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharpit.com/?feed=rss2&#038;p=11</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

