Dependency Frameworks and Parameterized Constructors

April 23rd, 2012 Comments off

Most dependency injection frameworks support some kind of object initialization through parameterized constructors. The question is whether or not it’s a good idea to use that feature of DI frameworks.

Consider the following code:
Read more…

MEF: Easily Creating Plug-in Based Apps In .NET

April 21st, 2012 Comments off

MEF (Managed Extensibility Framework) is an awesome framework that allows easily loading types at runtime making your apps plugin-ready.   Using reflection magic, MEF makes it super easy for any app to accept plugins.

Following are 5 easy steps involved in making your app plugin-ready using MEF:

  1. Define an interface for plugins.  This is the interface that each plugin must implement.
  2. Define a metadata interface.  This interface tells your app out of so many plugins which one is the correct plugin for a given piece of functionality.
  3. Define one or more concrete plugin classes.
  4. Decorate each class with some attributes.
  5. In your app write a few lines of code to invoke MEF, and let the magic happen.

Read more…

Complex Object Mapping Using AutoMapper

May 30th, 2011 Comments off

AutoMapper is an awesome open source library that allows automatic object-to-object mapping.  There are various getting-started blog posts and articles on the web (e.g. Getting Started Guide and AutoMapper on CodeProject) that will get you started with AutoMapper.  I was recently challenged with a particular situation using AutoMapper that wasn’t immediately clear and took me a little investigating and some trial and error work, so I will share that with you.

My source object exposed some simple properties as well as a generic List property of another type.  My target object had same simple properties, but the generic List property was of an interface type.  Following is a simplified illustration of my source and target objects:

Source Object

Target Object

A cool thing about AutoMapper is that when it encounters a target object of an interface, it automatically generates a dynamic proxy class using Castle Dynamic Proxy.  This is usually the desired behavior when mapping to a non-existent target class.  In my case, however, the target class already existed, and dynamic proxy was just an overhead.  I tinkered with AutoMapper mappings to actually map to my existing target rather than generating a proxy:

Essentially what I am doing in my mapping is to first create a map between my source and target Orders objects. Once that’s done, I create a map between my source and target Customer objects but provide a custom map for the Orders property. In my custom map I simply use AutoMapper to map my source Orders property to target Orders property using the map definition I provided earlier (lines 1-2 above). This works out great and I get my expected target object without incurring the overhead of expensive proxies.