Using C# 4 you can utilize lazy initialization for MEF. See Lazy<T,TMetadata>
.
// So I have this member, populated through MEF.
private Lazy<MyItem, ISomeInterface> item;
public Lazy<MyItem, ISomeInterface> Item
{
get
{
return item;
}
set
{
item = value;
}
}
Now, what if I have a MyItem
instance that I would like to assign to this lazy member variable? This does not work:
var myItem = new MyItem(); // Implements ISomeInterface
o.Item = myItem; // Cannot convert type...
UPDATE: I simplified my sample a bit too much. The problem here is that I have lazy-evaluated items (coming from a MEF
plugin manager) in terms of Lazy<MyItem, ISomeInterface>
. Sometimes these items are already instantiated which asks for a construct as follows:
var item = new Lazy<MyItem, ISomeInterface>(obj);
However, that causes a MissingMemberException
:
"The lazily-initialized type does not have a public, parameterless constructor."
Q: How do I assign a Lazy<T, U>
variable with an instance of T
(that implements U
)?
The solution is to use the ToLazy
method that MEF
uses:
https://mefcontrib.svn.codeplex.com/svn/trunk/src/MefContrib.Models.Provider/ComposableMember.cs