Reputation: 19937
Using C# 4 you can utilize lazy initialization for MEF. See http://msdn.microsoft.com/en-us/library/dd986615.aspx
// 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
)?
Upvotes: 0
Views: 1050
Reputation: 19937
The solution is to use the ToLazy
method that MEF
uses:
https://mefcontrib.svn.codeplex.com/svn/trunk/src/MefContrib.Models.Provider/ComposableMember.cs
Upvotes: 0
Reputation: 512
Or:
Item = new Lazy<Foo>
(
()=>
{
Foo fobj = new Foo() { ID = 99 };
return fobj;
}
);
Upvotes: 2
Reputation: 38590
I know it's called Lazy but you could at least read the docs! :)
o.Item = new Lazy<MyItem>(InitFunction);
Upvotes: 0