本文介绍了使用Autofac在特定名称空间中注入依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将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?

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

that Autofac does not provide this functionality, but some workaround could be applied.

谢谢!

(对不起,我的英语)

更改标题以获得更好的描述.

Edit 1: Changed title for better description.

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

Edit 2, 3: Changed contents and title for better description.

推荐答案

很抱歉回复缓慢.

您对Autofac最好的选择是使用规则注册ViewModel,并应用参数来解决ObservableCollection<>的不同实现:

Your best bet with Autofac is to use a rule for registering the ViewModels and to apply a parameter to resolve the different implementation of 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));

对于IsClosedTypeOf(),您需要为using Autofac;.另外,如果您使用的Autofac版本不支持WithParameter()的重载,则可以使用接受Parameter并传递ResolvedParameter的重载.

You'll need to be using Autofac; for IsClosedTypeOf(). Also, if the version of Autofac you're using doesn't support this overload of WithParameter() you can use the overload that takes a Parameter and pass a ResolvedParameter instead.

希望这会有所帮助,

尼克

这篇关于使用Autofac在特定名称空间中注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

查看更多