I develop wpf app with MVVM design. As MVVM framework I use Caliburn Micro. Service I have in external assembly, and it is injected in view models classes with MEF.
Problem in service I have many small class, I try respect SOLID principe.
[Export(typeof(IClassA)]
public class ClassA : IClassA
{}
[Export(typeof(IClassB)]
public class ClassB : IClassB
{}
[Export(typeof(IClassC)]
public class ClassC : IClassC
{}
//...
[Export(typeof(IClassK)]
public class ClassK : IClassK
{}
Classes count is about 12-15.
I need use this classes in view model class. So I use this:
public class MyViewModelClass
{
private interface IClassA _a;
private interface IClassB _b;
private interface IClassC _c;
//...
private interface IClassK _k;
[ImportingConstructor]
public MyViewModelClass(IClassA a, IClassB b, IClass c, ..., IClassK k)
{
_a=a; _b=b; _c=c; ... _k=k
}
}
I don’t that this way is correct. Or it exist something elegant, simple. Thank for your opinion and advices.
MEF can import to fields (even private ones). If you want to make your life a little easier, you can just decorate the fields with the ImportAttribute
. If you want to know when all the imports have finished, just implement the IPartImportsSatisfiedNotification
interface:
public class MyViewModelClass : IPartImportsSatisfiedNotification
{
[Import]
private IClassA _a;
[Import]
private IClassB _b;
[Import]
private IClassC _c;
...
public void OnImportsSatisfied()
{
// add initialization code here
}
}
This pretty much requires you to use MEF to ensure that your ViewModel is instantiated correctly, but depending on your scenario that may not be a big deal.