Autofac RegisterAssemblyTypes多次

时间:2019-12-09 07:40:28

标签: c# dependency-injection inversion-of-control autofac

我有带有多个视图模型和相应类层次结构的WPF应用程序。现在,我将Autofac用作IoC框架。我的结构看起来像这样简化:

public class ViewModelBase 
{}

public class ToolItemViewModel : ViewModelBase
{}

public class DocumentItemViewModel : ViewModelBase
{}

// Concrete implementations

public class MainViewModel : ViewModelBase
{}

public class EditorProperties : ToolItemViewModel
{}

public class TextViewModel : DocumentItemViewModel
{}

// Now in order to do something like this:

var mainViewModel = _scope.Resolve<MainViewModel>();
var tools = _scope.Resolve<IEnumerable<ToolItemViewModel>>();
var documents = _scope.Resolve<IEnumerable<DocumentItemViewModel>>();

// It seems I have to do the following registrations

builder.RegisterAssemblyTypes(typeof(App).Assembly).
    Where(t => t.IsAssignableTo<ViewModelBase>()).AsSelf();

builder.RegisterAssemblyTypes(typeof(App).Assembly).
    Where(t => t.IsSubclassOf(typeof(ToolItemViewModel))).As<ToolItemViewModel>();

builder.RegisterAssemblyTypes(typeof(App).Assembly).
    Where(t => t.IsAssignableTo<DocumentItemViewModel>()).AsSelf().
    Where(t => t.IsSubclassOf(typeof(DocumentItemViewModel))).As<DocumentItemViewModel>();

我可以避免在这里多次运行“ RegisterAssemblyTypes”吗?所有类都派生自ViewModelBase,所以我认为一个“ RegisterAssemblyTypes”就足够了吗?

1 个答案:

答案 0 :(得分:0)

你不能。 Autofac 需要对每种类型进行多次调用(我也发布了链接):

https://autofaccn.readthedocs.io/en/latest/register/scanning.html

扫描类型 也称为约定驱动注册或扫描,Autofac 可以根据用户指定的规则从程序集中注册一组类型:

SQSEvent

每个 RegisterAssemblyTypes() 调用将仅应用一组规则 - 如果要注册多组不同的组件,则需要多次调用 RegisterAssemblyTypes()。