Getting Lazy with MEF

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434