Showing posts with label MEF. Show all posts
Showing posts with label MEF. Show all posts

2009-05-30

Generics instantiation using MEF

This post will discuss techniques of instantiating generics types at runtime.

You can download the code sample here.

Generics has lots of benefits (which is not the subject of this post).
In order to gain most of the generics benefits you should instantiate the generics at design time whenever it possible.
But using generics long enough you come across needs of instantiate the generics at runtime (mostly because there is scenarios when you don’t know the exact type of T at design time.

How can you instantiate generics at runtime?

you can instantiate it at runtime using reflection, as the following code demonstrate (but it is very expensive instantiation technique):

public class MyGenericType<T> {
public MyGenericType ( T instance ) {
this.Instance = instance;
}
public T Instance { get; set; }
public static object Create ( object body ) {
Type gnType = typeof (MyGenericType<>);
Type[] typeArgs = { body.GetType () };
Type genericType = gnType.MakeGenericType (typeArgs);
object o = Activator.CreateInstance (
genericType, body);
return o ;
}
}

The above code has simple generics class with static Create method which use reflection in order to instantiate the class

How can we improve it?

We can use the factory or DI (dependency injection).
Factory code will look something like the following code:

public static object Create ( object body ) {
if (body is string)
return new MyGenericType<string> (body as string);
if (body is DataTable)
return new MyGenericType<DataTable> (body as DataTable);
throw new NotImplementedException()
}

The problem is this, writing hardcoded factory case extensibility problem which require recompilation whenever new type should added and cross reference conflict in-case that the new type locate in dll that already reference our assembly.
So obviously you can use DI to solve the problem (which is good acceptable solution)

Taking it one step further

I choose different approach which is using the newly MEF technology for addressing this problem by Exporting the factories as MEF export parts.
The following code assume that you are familiar with the MEF fundamentals (if not you should read this post):

[Export (typeof(MyFactory))]
[PartExportsInherited]
public abstract class MyFactory {
public abstract object Create(object bodyOfMsgBase);
public abstract bool CanHandle<T> ();
}
public class MyFactoryOfDataTable: MyFactory  {
public override object Create ( object bodyOfMsgBase ) {
return new MyGenericType<DataTable>(bodyOfMsgBase as DataTable);
}

public override bool CanHandle<T> () {
return typeof (DataTable) == typeof (T);
}
}

You can later consume the factory as demonstrate in the following code:

var container = new CompositionContainer (
new AssemblyCatalog(Assembly.GetExecutingAssembly()));

ICollection<MyFactory> aPlugIns=container.GetExportedObjects<MyFactory>();
var plugIn = (from item in aPlugIns
where item.CanHandle<string>()
select item).SingleOrDefault();
var instance = plugIn.Create (“Hellow world”);

Summary
We so that creating generics at runtime is possible but it can be costly using reflection.

You can download the code sample here.

2009-05-16

MEF introduction

The MEF team declare the MEF as

“The Managed Extensibility Framework (MEF) is a new library in .NET that enables greater reuse of applications and components. Using MEF, .NET applications can make the shift from being statically compiled to dynamically composed.”

you can download the MEF bits in here

SO what is the MEF and why do you want it?

Lets start with what !(MAF)
MEF is not another DI (dependency injection), you should think of MEF as plug-ins infrastructure rather then being DI.

Actually you can consider MEF as very flexible plug-ins discovery mechanism.

How does it work?

The essence of MEF paradigm is built upon the idea of needs and part that can be founds (in order of satisfying the needs).

You can think of it as having Guilds that publish its policy (shoemaker, tailor, ext…), and Peoples that declaring their professions, the MEF infrastructure apply the role of matching the Peoples to their suitable Guilds.

image

The above diagram present institutions (University and software company) that has specific need (in terms of human segments),
and peoples that apply to one or more of the segments.
the MEF framework role is to satisfy the institution needs by discovering the people which apply the right segments.

The MEF terminology: institutions will be declare as Import and the peoples will be declare as Export Parts

Where does MEF looking for the for its Export Parts?

MEF is looking for export parts in Catalogs there is built-in catalogs (like Directory, Assembly, Types) and you definitely can build your own.

Code samples:

You can download the sample here (VS 2008 SP1)

the following are very light snippets of how it will look

// property that declare its needs for university related peoples
[Import (typeof (IUniversityRelated))]
public IEnumerable<PeopleBase> Peoples { get; private set; }
// class that decorate export part for university
[Export (typeof (IUniversityRelated))]
public class Student: PeopleBase, IUniversityRelated
// asking the MEF to compose the right export parts
// in order of satisfying the imports

private static CompositionContainer s_container =
new CompositionContainer (new AggregateCatalog ());
static void Main ( string[] args ) {

// here the MEF magic matching game occur
s_container.Compose (new CompositionBatch ());

Summary

MEF is very friendly plug-ins framework which help you to get greater extensibility with less efforts and more consistency.
It is very simple decoration module which having supper light dependencies.I hope you find this post useful, I'm having intensions to write future post which will cover the MEF in more details including some advance technique.

About

Bnaya Eshet C.T.O and co-founder of Wise Mobility