Reputation: 498
I really think this is not asked yet and not sure if anyone has run into this issue before
So I am working with MEF and have a class like below -
[Export]
public class MyClass : IBase
{
private IEnumerable<IMyAddin> _theAddin;
// Default constructor will NOT be
// used because the ImportingConstructor
// attribute is present.
public MyClass()
{
foreach (var addin in _theAddin)
DoSomeVeryImportantWork(addin);
}
// This constructor will be used.
// An import with contract type IMyAddin is
// declared automatically.
[ImportingConstructor]
public MyClass([ImportMany]IEnumerable<IMyAddin> MyAddin;) : this()
{
_theAddin = MyAddin;
}
}
I have a method somewhere like below -
T GetById<T>(Guid id) where T:IBase, new()
{
var x = new T();
//Do some processing
return x
}
Problem is, since I am doing a new T(), default constructor doesn't know anything about _TheAddin
and is null.
Has anyone faced this before? Please let me know if the question is not clear, I can provide more details.
I have tried removed [ImportingConstructor]
from the default constructor, but it doesn't work. How do I populate _theAddin
?
Thanks in advance!
Edit: I have also tried as below, doesn't work -
[Export]
public class MyClass : IBase
{
[ImportMany]
private IEnumerable<IMyAddin> _theAddin;
// Default constructor will NOT be
// used because the ImportingConstructor
// attribute is present.
public MyClass()
{
foreach (var addin in _theAddin)
DoSomeVeryImportantWork(addin);
}
}
Upvotes: 0
Views: 301
Reputation:
You might want to create the underlying CompositionContainer yourself and provide some static methods to retrieve objects from it. You could also expose your container directly so that you can access methods like SatisfyImportsOnce(), GetExport() etc. from anywhere.
Note: you can get rid of the ctor that does the import and decorate your private field directly with [ImportMany]. This way after creating a new T() you could call yourContainer.SatisfyImportsOnce(your_T_instance).
See the example on msdn for details.
Upvotes: 0