在视图模型类中注入许多类
我使用 MVVM 设计开发 wpf 应用程序。作为 MVVM 框架,我使用 Caliburn Micro。我在外部程序集中拥有服务,它使用 MEF 注入到视图模型类中。
服务中的问题我有很多小班,我尝试尊重SOLID原则。
[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
{}
班级人数约为12-15人。
我需要在视图模型类中使用此类。所以我用这个:
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
致:阿贝·海德布雷希特。
我有点困惑。如果我用这个:
因为。
IPartImportsSatisfiedNotification 只有一个方法:OnImportsSatisfied,当所有可以满足的导入都已满足时调用该方法。
我认为在视图模型类的构造函数中对服务类的初始化接口进行单元测试更好。
To: Abe Heidbrecht.
I am little confuse. If I use this:
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.
MEF 可以导入到字段(甚至是私有字段)。如果您想让您的生活更轻松一些,您可以使用
ImportAttribute
修饰字段。如果您想知道所有导入何时完成,只需实现IPartImportsSatisfiedNotification
接口:这几乎需要您使用 MEF 来确保正确实例化您的 ViewModel,但根据您的场景,这可能不会是一件大事。
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 theIPartImportsSatisfiedNotification
interface: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.