This article describes differences between MEF and Unity which may help you in deciding which technology you must use while making composite application.
Both technologies are useful and easy to understand, and offer a rich set of features that can make integration of various software components very easy. However, both being little different in functioning they offer exact same level of features but choosing wrong one can lead to chaos.
So we will drill down to differences between their operations.
Unity creates new instance of type by default.
MEF creates singleton instance of type by default.
Unity does not require registration for classes. This means you can instantiate any other third party type.
MEF requires Export attribute to be specified on the class. MEF cannot create instance of third party type unless it defines Export.
Unity requires type registration in code for interface types.
No registration, simple Export attribute does it all.
Unity container can compose IUnityContainer property in the composed class where you can further access it easily in your own scope. This behavior is not useful for Plugin architecture as getting access to IUnityContainer may result in full access to your application.
MEF does not allow composition of CompositionContainer, which blocks access to MEF in your own scope if you do not have CompositionContainer. This is useful in Plugin architecture where third party code has limited access to your application.
Unity offers injection method mechanism, that can define IUnityContainer parameter and get the unity container object, with which you can compose other private properties manually.
MEF can only compose public properties, this is dangerous as anyone can change public property and make application crash easily.
Inside your application’s framework code, Unity serves the best as it gives you full control over type hierarchy, lifecycle and allows you to utilize third party components easily without writing much of code.
Inside your application, MEF will put lots of restrictions in which your framework can operate as it cannot easily compose third party components and it will force you to write numerous attributes in your code without which it will fail drastically.
Mostly, User Interface objects like your View, or UserControl or any UIElement can never be shared as no UIElement can have two parents at same time. So default behavior of Unity to create a new instance of type is very helpful.
Default behavior of MEF will create only one single instance of UI object, that will lead to trouble, not only that, if UI object is third party tool, MEF will not compose it. You can create multiple copies of exported type by specifying one more attribute called [PartCreationPolicy(Shared)], however it is very time comsuming and tedious to define this one every UI related type we create.
Unity does allow singleton objects, but for that you have to register an instance to the container.
MEF by default creates singleton object only.
Unity does not allow multiple registrations for same instance in same scope sharing same interface but different type.
MEF allows multiple singleton objects of different type sharing same interface.
Unity works best for MVVM, as composing user interface parts can be very easy with unity.
MEF does not work great with MVVM as it will create singleton objects that will behave strangely in runtime and lead to UI failure.
Unity is not good for Modularity, as composing IUnityContainer will offer more control of unity lifecycle to third party modules.
MEF is good for Modularity, as it will not allow modification of composition thus offering great deal of security between modules.
So, to develop a framework, MVVM Crud application and a UI framework, Unity is the best.
To expose some functionality of your application for third party modules to register and access limited functionality, MEF is the best.
Following is outline of how your application should be,
Unity Container must compose and manage your application’s framework, UI and MEF modules.
MEF will only expose limited functionality from Unity Container to third party modules.
No module, through MEF should have access to unity container at all.
Thank you for reading this article, please put your suggestions below in the comment. I do not intend to make any specific rules and regulations here but I am suggesting the architecture based on the differences I have outlined.
We are happy to announce new release of UI Atoms 1.7.5 with following new features.
- New AtomDataForm Control
- Tabs in AtomForm and AtomDataForm
- Lambda Binding Extensions
Introducing new Control AtomDataForm
AtomForm did support UI Validations, however Microsoft RIA Services Client has some inbuilt validation and support for IEditableObject. So we created a new AtomDataForm that supports RIA Services validation and IEditableObject support.
- AtomDataForm supports object with IEditableObject interface and fires event for BeginEdit, CancelEdit and EndEdit
- AtomDataForm displays items in read only mode unless Edit button is clicked
- After edit button is clicked, Save and Cancel button appear for you to persist changes or cancel changes
- AtomDataForm contains UI Element (TextBox, ComboBox etc) as children, so you can easily define child ui element in your xaml as shown in sample below
- AtomDataForm supports Tabbed layout, for that you can insert your items within AtomDataFormTab as shown in example below
- Following sample illustrates Tabs, but you can also create simple user interface without tab as well
- You can also use AtomDataFormGroup to group items in to a headered group
- Every child element of AtomDataForm can be accessed in code behind file easily because they appear as a variables when you define x:Name property
- AtomDataForm supports CanChangeDataContext property, which is false when the form is in edit mode
- You can easily reuse any third party control within AtomDataForm, AtomDataFormGroup and AtomDataFormTab
In above sample you can notice following things,
- Header property of AtomDataFormTab is displayed in the title section on the top
- AtomDataFormTab contains children and each child can have properties as below
- ns:AtomDataForm.Label displays label on left side
- ns:AtomDataForm.Description displays description on bottom
- ns:AtomDataForm.Title displays title on the top of control
- ns:AtomDataForm.CommandBox displays a UI Element on the right corner, usually a search button or expand button
- AtomDataFormTab supports IsEnabled binding, you can bind this property to show/hide the tab as shown in the example above
- Every child elemen of either AtomDataForm , AtomDataFormTab or AtomDataFormGroup supports Visibility and IsEnabled binding
- If Visibility is bound and it results in Collapsed then entire form item is not displayed
- IsEnabled binding can enable/disable the editable control
Following is screenshot of Tabbed AtomDataForm in edit mode
Introducing Lambda Binder Extensions
Writing binding expressions with conditions and converters can be very complex especially rewriting many and same logic at different classes. Now UI Atoms support, Lambda Binding Extensions which lets you do binding within the code without creating any complex IValueConverter implementation.
Bind Method Extension
This will bind theForm’s Header property to an expression that will combine properties of two different elements. And this will also automatically update when any of bound source or its property will change.
Assuming, we may not have property information at design time, but we know that DataContext will be set to an object containing properties, then we can write Property extension method as shown above.
BindVisibility Method Extension
Visibility converters are very frequent so we created a BindVisibility extension method that will let you specify a boolean expression that will be converted to Visibility on the fly.
These extensions can be used anywhere in any third party controls as well.
Click here to download your free demo copy of NeuroSpeech UI Atoms 1.7.5
LambdaBinder class helps in creating complex binding expressions without having to create IValueConverter and IMultiValueConverter, it lets you write inline expresions with advanced binding scenarios.
Lets say, you have two TextBox for first and last name and you want a Title to be displayed as addition of both.
So lets say, you can write it as follow,
You can pass on the Linq expression to Bind extension method of LamdaBinder and that will convert and set binding so that anytime if firstName or lastName is modified, the title will be updated automatically.
Assuming I want some hypothetical visibility logic, for example, only if the firstName is entered, lastName should be visible.
You can also use this to avoid writing IValueConverters and do inline binding in code very easily.
LambdaBinder is part of UI Atoms suite. At NeuroSpeech, we do research on UI and we are coming up with more interesting featues in UI Atoms.
Please Click Here to download latest update of UI Atoms with AtomForm including Tabs in the form.
Entity Framework and RIA Services do not allow Entities to be added/removed from cross containers. In order to move Entity from one DomainContext/ObjectContext to another DomainContext/ObjectContext, we need to recursively detach the object graph and attach it to other DomainContext/ObjectContext.
Single entity can be easily detached and attached from EntitySet where it belongs, but the problem comes when navigation properties of entity are not empty. Entity object along with navigation properties is called Object Graph because if you notice, navigation property’s navigation property will contain reference to same entity and that will result in endless recursive code for Detach/Attach.
An entity with the same identity already exists in the EntitySet
When you try to detach entity from old DomainContext/ObjectContext and attach it to DomainContext/ObjectContext, it may give you an error that entity with same identity already exists and it will throw an exception. In this case we will just simply reuse the existing entity instead of attaching the entity we have.
Entity cannot be attached to this EntityContainer because it is already attached to another EntityContainer
In case of ObjectGraph, your root level entity is already detached, but navigation properties are not detached, and while you try to attach your root level entity, it will throw same error for entities that exist in navigation properties. Because detach method does not recursively detach every entity from navigation properties.
Attach/Detach Extension Methods
Finally after brainstorming little, I made following class that will allow you to recursively detach/attach object graphs from DomainContext. You can replace DomainContext to ObjectContext to use it inside Entity Framework.
We are happy to announce new release of UI Atoms 1.5.8 with following new features.
UI Atoms for WPF 4.0
In this release of UI Atoms, we have a new library of dlls specially designed for WPF 4.0, which now includes support for Visual State Managers and renders everything in WPF 4.0 presentation. You can find Bin.Net4 folder inside WPF, that contains libraries only for WPF 4.0 version.
AtomForm Label Alignment for Silverlight and WPF
AtomForm now provides following two properties,
- LabelHorizontalAlignment property that can align the label horizontally in the form item.
- LabelVerticalAlignment property that can align the label vertically in the form item.
Label Can now contain string or UI Element object
Advanced Quick Form Designer
Typing Tags with all Bindings could be quite time consuming, where it involves moving items up and down, deleting and adding new Form Items. Advanced Quick Form Designer resolves all this problems by giving you state of art designer, which provides one quick grid to enter all necessary information. However the form designer works well even for existing forms, and you can generate entire new form by selecting some Type as well.
As you see, type of control can be changed that will represent the form item and corresponding binding property can be changed as well. Just with simple one click, you can move items up and down or delete them. You can add a new control that is defaulted to AtomTextBox at the top, you can change default control to add multiple one after another very easily. Also you can click “Generate From Type” to select any Business Object Type and generate a brand new form.
Selecting type will automatically generate form with its bindings.
UI Atoms version 1.2.22 resolves Cascaded ComboBoxes issue in MVVM pattern. Advanced AtomForm is now capable of handling cascaded ComboBoxes with MVVM and it also integrates well with third party controls.
Recently we identified few issues with MVVM implementation in Silverlight regarding ComboBoxes. ComboBox looses its “SelectedValue” binding once the ItemsSource of ComboBox changes. This needed some workaround as well as Modifying DataForm is very painful as you may need very complex form designs in regular business applications.
1. Create Models
Lets assume we need to edit a Customer’s Country and City, as we change the Country the list of cities should change it. Problem with existing ComboBox and DataForm is, as soon as list of cities changes, ComboBox’s SelectedValue binding vanishes. So lets create Customer Model first.
Each of properties in CustomerViewModel raises PropertyChanged event for corresponding properties when modified.
When selected customer changes, SelectedCountry also changes and which changes Cities property, so in drop down we can display the list of cities of selected country.
Your SelectedCountry property, where you need Change of Selection event must not raise PropertyChanged event in “set” method as shown below…, however you may turn it off or on based on your UI behavior. WPF has no problem but Silverlight has issues and it works better if PropertyChanged event is not raised.
2. Create Master View
Master View control declares grid with two columns, left side displaying list of customers and on right side displaying details of the selected customer.
Lets analyze Bindings,
- ListBox’s ItemsSource is bound to ViewModel.Customers which returns list of available customers.
- ListBox’s SelectedItem is bound (two way) to ViewModel.SelectedCustomer.
Lets analyze the bindings,
- AtomForm’s DataContext is bound to SelectedCustomer of ViewModel, which comes from SelectedItem of Parent Control
- AtomTextBox’s Text is bound to Name (of AtomForm’s DataContext’s binding) with Mode=TwoWay
- ItemsSource is bound to ViewModel.Countries which returns list of countries.
- SelectedValue is bound to CountryID (of AtomForm’s DataContext’s binding) with Mode=TwoWay
- SelectedItem is bound to ViewModel.SelectedCountry, which triggers change of SelectedCountry property on ViewModel which changes list of cities.
- AtomComboBox (this is the one that’s tricky, normal ComboBox does not work here)
- ItemsSource is bound to ViewModel.Cities which returns list of cities of SelectedCountry.
- SelectedValue is bound to CityID (of AtomForm’s DataContext’s binding) with Mode=TwoWay
3. Cascaded ComboBox
You can see that the cascaded ComboBox work well with AtomForm and AtomComboBox and its easy to design AtomForm with MVVM with so much less code then that of DataForm and ComboBoxes.
Please download the latest version of UI Atoms 2010 suite to try MVVM + AtomForm + Cascaded ComboBoxes.
XamlGenerator is Code Behind source code Generator for Xaml.
Xaml Code Behind Generator makes it easier to generate Code Behind designer code from XAML, where code can be used at places where Xaml Services are not accessible.
- Using XAML 2009 in Silverlight and WPF
- Reusing Xaml Business Pages in Silverlight and WPF
- Support for User Controls derived from any Control
- Using Complied code instead of BAML
- Improving speed of XAML runtime
- Using XAML to generate code to be used in ASP.NET, Server Core etc, where XAML Services are not available
- Generated code is pure .NET 2.0 compliant, and you can target xaml objects to run in earlier .NET version too.
- You can also create Xaml for WinForms and use it for your .NET 2.0 projects, however please notice, the features of WPF will not be available, it can only create object hierarchies based on XAML, but it can not give you binding etc features.
- x:Name support for Resources, very useful for MVVM Pattern
- Support for Custom Extension with Custom Code Generator
Xaml Code Generator
.Net 4 introduces Xaml Services that can load Xaml Object Trees and it provides great deal in terms of intellisense and code behind facilities, however this can only be used where Xaml Services are installed. Also it is quite painful to debug and hide the generated baml resources, that actually is quite easy to disassemble and view the source.
Xaml Code Generator can easily solve these problems by creating source code equivalent to loading object via Xaml Services. Instead, once generated, the performance of source code is quite faster then baml and xaml. Since ASP.NET and WinForms, code behind files did serve great support to link the UI and Code. However in WPF and Silverlight does not support simple references to code behind objects except events. There are work arounds, but we decided to create Xaml Code Generator that will solve lot of problems.
Benefits to WPF and Silverlight
- Xaml pages can now use x:Reference markup extension
- Xaml pages can support generic type parameters
- Xaml page can now derive from any control/panel
- Xaml can easily reference any expression that involves code behind operation including "this" keyword
- By using custom Xaml markup extensions, you can reuse Xaml between WPF and Silverlight
Known limitations with Xaml Code Generated files
- Control Templates and Styles must use respective WPF/Silverlight markup only
- No code behind files can be generated for Control Templates and Styles
- Xaml pages can not be used with Navigation Urls
- Instead code generated files are simply source code equivalent of Xaml, and they should be treated as .Net CLR Objects instead of Xaml Pages and there exists no equivalent baml resources
So how to use benefits of Code Generator as well as XAML
We recommend following pattern to make use of best of both the worlds
- Create Main Application Window/Page as regular Xaml
- Instead of User Controls, use Xaml derived from Equivalent controls, such as StackPanel, Grid etc, and use them in Main Window/Pages
- In this pattern, generated CLR objects of xaml will perform exactly same
Why Generate source code from XAML?
Xaml and Xaml Services are great, they give a huge benefit in terms of runtime model loading and behaviour. For larger systems, and for complex enterprise applications Xaml is perfect. But we still have lot of code in .NET 2.0 and applications that are still heavily dependent on the components that do not support Xaml Services.
Plus, shift of paradigm from code behind to view model is quite painful. Infact ability to use more code behind features is quite needed for current generation.
Debugging Xaml is quite painful still, we still have lot of logic that lies in functional code and there is little more time still before we reach to completely modelled code.
Here are few benefits outlined of generated code,
- View Model can be replaced by Code behind, as we can easily reference xc:This and xc:Ref extensions
- Debugging c# code can be easier which involves more complex UI designs
- Xaml Generated can generate anything, even non UI code
- You can even use Xaml Generator in your DSL tool
For more details, please visit, http://xamlgenerator.codeplex.com/
This tutorial outlines how to customize UI Atoms’ AtomForm appearance and layout simply by customizing its ItemContainerStyle.
AtomForm is derived from ItemsControl, and ItemsControl declares ItemContainerStyle which can customize the template of individual items that are being displayed. UI Atoms give you complete freedom of how to change your look and feel very easily by just adding a simple template in your resource dictionary.
Create New Item Container Style
To do this, open your xaml page in the Expression Blend and right click on the AtomForm. And choose Edit Additional Templates, and Select Edit Generated Item Container (ItemContainerStyle) and then click on “Edit a copy…”
Then choose a location to keep your style in,
Once the style editor is open, right click on “Style” and click on “Edit Template” and then click on “Edit Current”
Now you will see the Item Container Style’s current Form Item template. Where you can change the colors and layout, for example, we have modified the Vertical Layout of “PART_Label” field as Top in this figure below.
RIA (Rich Internet Application) means faster means to develop light applications to fit in your business presentation and few quick interactive applications. With RIA you can not make a money tree and you can not become rich.
- Frontend Applications
- Small Quick Demo Applications
- Graphical Analysis of MIS
- Marketing Presentations
- Quick Forms/Data Entry for Mass Audience
- Polls, Social Interaction Applications
- Thin Client Applications
With RIA you can generally make a thin client applications, which surely needs to interact with high poerful web server or any other form of server over internet. RIA replaces frontend for modern internet applications from traditional HTML/JS form processing websites.
Traditional web portal applications (ASP.NET/EJB..) takes too much of time to process every single request, as it does not use full potential of client side computer. Every decision of which button to be displayed, state of an application and user’s choices and preferences, everything is maintained on server and applications utilizes too much of bandwidth as well.
Thats why, RIA is simple step to differentiate user interface and business logic completely with implementations of standards like SOAP web services and REST apis.
All RIAs are compiled at development site, that means the final RIA is in form of an application, which will execute accurately as designed. However in traditional HTML+JS, if any part of HTML is not rendered properly or its coded wrongly, there is no way to detect until it is delivered to browser and some error has been encountered. Pre compilation on RIA, reduces time required to develop web application drastically.
(I am talking about FLEX not Flash)
Community Support is very bad when you need quick solution in an emergency.
|Paid Support & Community||Paid Support & Community||Community Support||Community Support|
|Dependency||Flash Player||Silverlight Player||Java Runtime + JavaFX Runtime||XUL Runtime|
According to various statistics, the by default availability of dependent software on PCs.
Although few PCs and all MACs have Java Runtime, they still need something additional.
|30% as FireFox supports XUL Apps|
|Size of Runtime||1MB||4.5MB||30MB||4MB|
|Native Device Access||Camera, Mic and Speakers||Speakers||Speakers||None in Web App,
May be few in Desktop App
|Audio Video Support||Widely used FLV and MP3 format, stable and its there since 2001||WMV/WMA/WMA Pro||No||No|
|Converters for the Supported Video||FFMPEG and many other commercial vendors available||Paid Encoders||No||No|
|Documentation||SDK Documentation and Samples||MSDN but still very premature, (Reason, the learning curve is little higher)||JavaDocs but JavaFX is still new||Apache Documentation, very scattered, difficult to learn.|
|Syntax||XML + Action Script||XML + C# / JS / VB.NET||Totally New Syntax||XML + JS|
|Language Feature||Strictly Typed with “Object” being dynamic type||Strictly Typed,
Dynamic type to come in C# 4.0
|Strictly Typed||Dynamic Typed|
Flex introduced wonderful concept of auto updating expressions when properties or variables changes.
|Very Accurate||Accurate but lengthy code||Available||Better then JavaFX and Silverlight|
|Two Way Databinding
||Not Available, Coming up in Flex 4||Available||-||Available|
|Binding Declaration||Simple Attribute||Extra Code in each bindable property||Extra code in each bindable property||Simple Attribute|
|Code Size||Very Concise||Even simpler things like validator etc takes 6 lines, too big code size to maintain||Size is small, but very disorganized, difficult to read||Concise enough|
|Platform Availability||Windows, Mac, Linux||Windows Only||Windows, Mac, Linux||Windows, Mac, Linux|
|Stability||Very Stable||Pre Beta||Pre Beta||Stable Enough|
|Control Library||Rich set of Controls available, plus lots of free stuff available as well||Very basic controls, you have to spend money on other ISVs to get good controls||Good set of Controls||Almost everything is free, lacks good documentation though|
For project managers, how difficult it will be to find coders who will code.
|Easily Available as existing Flash, HTML, JS, ActionScript can code.||C# and Microsoft Technology programmers can code.||Java Programmers can code, but due to new syntax, its still difficult to get hands on it.||Very difficult as it requires too extra knowledge of mozilla architecture and various standards, which is not taught anywhere.|
Starting project is very easy, but ongoing maintanence and meeting deadlines requires excellent knowledge of technology, which you should not rely on community blogs, because time required to search any solution is costly.
|Themes/Skinning||Yes||Yes, but size of code is very big||No||Yes|
|WebService Integration||Yes||Yes||Yes but very frustrating||Yes|
|Upload/Download||The Best Feature in Flex||Yes||Yes||Yes|
|Installable on Desktop||Yes||No||Yes||Yes|
|Database Support (in desktop app only)||Sqlite||Not Applicable||JavaDB
Too heavy and too slow
|Auto Update on Desktop App||Yes||No||No||Yes|
Plugins are available under eclipse and netbeans etc type of editor, but problem is they are so premature, they dont support refractoring, analysis, debugging and lots of other facilities.
|Flex Builder||Visual Studio||Plugin||Plugin|
|IDE Source Versioning||CVS
Good for Multiusers
|Source Safe (Single Developer only)/ TSS (too costly)||Plugin||Plugin|
|Drag and Drop Editor||Yes||Limited, because to script you need Visual Studio and to design you need Blend (Other paid software)||No||No|
|Code Intellisense (Auto Complete)||Yes||Yes|
Creating and importing shared code in the form of libraries.
|Component Development||Very Simple||Quite Complex as it is divided in User/Custom controls categories.||Available||Simple|
||Leader of RIA||Flex Follower||The Last||Linux Love|
Silverlight claims to be platform independent, but reality is, Microsoft no longer provides any more upgrades of Silverlight version for any other operating system other then Windows. And Linux was already not officially supported by Microsoft.
Advantages of RIA
- Reduce Development time
As compared with traditional web application, since RIAs are pre compiled, errors due to syntax, wrong spellings can be detected earlier at time of desiging.
- Load First, Run Throughout
RIAs load entire application (Except XUL) in the beginning, instead of HTML+JS, which loads as things proceed. This means, either application will load completely and work accurately even with slower bandwidth connection, or if some part didnt load, it will straightway display an error. So it works like transaction, either all or nothing. HTML+JS can behave unexpectedly in case of missing components.
- Seperate Design and Development Processes
Flex and Sliverlight offers complete seperation of Development and Designing keeping integration simple, other platforms (earlier web ones) require too much time integrating designs and process.
- Utilize Client Computing
Almost every computer has high powerful graphics capabilities, HTML/JS doesnt offer any great benefit over it. RIAs can completely explore native graphics capabilities and you get wide range of user interface functionality.