问题描述
我想将DispatcherNotifiedObservableCollection作为ObservableCollection注入(并且仅注入)所有ViewModel(位于MyProject.ViewModels中).
I want to inject DispatcherNotifiedObservableCollection into (and only into) all ViewModels (located in MyProject.ViewModels) as ObservableCollection.
使用Ninject我可以通过以下方式完成此操作:
With Ninject I can accomplish this with:
Bind(typeof(ObservableCollection<>))
.To(typeof(DispatcherNotifiedObservableCollection<>))
.When(context => context.ParentContext.Binding
.Service.Namespace == "MyProject.ViewModels");
我从尼古拉斯·布鲁姆哈特(Nicholas Blumhardt)了解到: Autofac与Ninject上下文绑定?/a>
I've learned from Nicholas Blumhardt: Autofac vs Ninject contextual binding?
that Autofac does not provide this functionality, but some workaround could be applied.
Edit 1: Changed title for better description.
Edit 2, 3: Changed contents and title for better description.
推荐答案
您对Autofac最好的选择是使用规则注册ViewModel
,并应用参数来解决ObservableCollection<>
的不同实现:
// Default for other components
builder.RegisterGeneric(typeof(ObservableCollection<>));
// Won't be picked up by default
builder.RegisterGeneric(typeof(DispatcherNotifiedObservableCollection<>))
.Named("dispatched", typeof(ObservableCollection<>));
var viewModelAssembly = typeof(AViewModel).Assembly;
builder.RegisterAssemblyTypes(viewModelAssembly)
.Where(t => t.Name != null && t.Name.EndsWith("ViewModel"))
.WithParameter(
(pi, c) => pi.ParameterType.IsClosedTypeOf(typeof(ObservableCollection<>)),
(pi, c) => c.ResolveNamed("dispatched", pi.ParameterType));
这篇关于使用Autofac在特定名称空间中注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!