使用Autofac在特定的命名空间中注入依赖项

3 autofac

我想将DispatcherNotifiedObservableCollection注入(并且只进入)所有ViewModel(位于MyProject.ViewModels中)作为ObservableCollection.

使用Ninject我可以通过以下方式实现此目的:

Bind(typeof(ObservableCollection<>))
    .To(typeof(DispatcherNotifiedObservableCollection<>))
    .When(context => context.ParentContext.Binding
        .Service.Namespace == "MyProject.ViewModels");
Run Code Online (Sandbox Code Playgroud)

我从尼古拉斯· 布鲁姆哈特那里学到了:Autofac vs Ninject的语境绑定?

Autofac不提供此功能,但可以应用一些解决方法.

谢谢!

(对不起我的英语不好)

编辑1:更改标题以获得更好的描述.

编辑2,3:更改内容和标题以获得更好的描述.

Nic*_*rdt 8

抱歉回复缓慢.

使用Autofac最好的办法是使用规则来注册ViewModels并应用参数来解决不同的实现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));
Run Code Online (Sandbox Code Playgroud)

你需要是using Autofac;IsClosedTypeOf().此外,如果您正在使用的Autofac版本不支持此重载,则WithParameter()可以使用带有a Parameter和传递的重载ResolvedParameter.

希望这可以帮助,

缺口