Getting Lazy with MEF
By | September 2, 2011

Lazy is a class that defer the object creation when it is actually needed. MEF supports the Lazy implementation internally. The Lazy type actually wraps around a type and creates the object of the type when the object is actually needed and used. I have written a post on Lazy implementation in .NET few months ago. In this post, I will not recap the whole thing, rather show you how MEF supports Lazy implementation.

In MEF, objects once exports are either imported in actual object or imported in Lazy form of Actual object. Lazy is actually used when your plugins are heavy and need large amount of memory. Therefore the objects will not be created when you ComposeParts for the CompositionContainer rather than it produce the Lazy implementation of the same and you can defer object creation when it is actually called for. Lets look how it works.

Working with Lazy is very simple. We just need to wrap the object that needed to be imported as lazy using Lazy block.

So instead of

[Import]
public MyType ImportedType { get; set; }

we just replace it with

[Import]
public Lazy ImportedType { get; set; }

This ensures that the object is actually not created when it is composed rather it is wrapped around the Lazy implementation.

You can use the same thing using ImportMany too.

[ImportMany]
public IEnumerable>> GetNames { get; set; }

So here the Func method getNames are not actually created, or rather assigned, but it forms a Lazy implementation for the same which will be automatically construct the object when Value is called.

How it happen automatically

Yes, this question might come in your mind. How this can be so easy. Actually the MEF team really looked around the thing and designed the software in such a way that it internally supports the Lazy implementation. It internally examines the Type of the ImportDefination, and assigns a Lazy implementation of actual object automatically when it is required.

Generally it is better to use Lazy when you want to Import an user interface to your application.

I hope this post comes handy.

Read more about it from the links :

Managed Extensibility Framework – A Look

Steps to write a plugin based application with MEF

Thank you for reading.