user572844
user572844

Reputation:

Inject many classes in view model class

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.

Upvotes: 0

Views: 557

Answers (2)

user572844
user572844

Reputation:

To: Abe Heidbrecht.

I am little confuse. If I use this:

public class MyViewModelClass : IPartImportsSatisfiedNotification
{
    [Import]
    private IClassA _a;  // I need init _a?
    [Import]
    private IClassB _b; 
    [Import]
    private IClassC _c;

    ...

    public void OnImportsSatisfied()
    {
        // what code must be here ?
        //how can I check if all import was success
    }
}

Because.

IPartImportsSatisfiedNotification has only a single method: OnImportsSatisfied, which is called when all imports that could be satisfied have been satisfied.

I think it is better for unit testing init interfaces of services class in contstructor of view model class.

Upvotes: 1

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

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.

Upvotes: 0

Related Questions