c# - 如何在 MVVM Light SimpleIoc 中注册一系列依赖项

标签 c# generics mvvm-light ioc-container

我想在我的 View 模型定位器类中注册和取消注册我的 View 模型。

我想要收集所有 View 模型并迭代它们以注册和取消注册它们。处理注册的方法声明如下:

public bool IsRegistered<T>();
public void Register<TClass>() where TClass : class;
public void Unregister<TClass>() where TClass : class;

我有以下许多组来注册它们:

if (SimpleIoc.Default.IsRegistered<SettingsViewModel>() == false)
{
    SimpleIoc.Default.Register<SettingsViewModel>();
}

并取消注册它们:

SimpleIoc.Default.Unregister<SettingsViewModel>();

我想 foreach 这段代码,所以我只有一个地方来声明我的 ViewModel。我无法获得正确的语法来执行此操作。

//Incorrect non compiling code
foreach (Type viewModel in ViewModels)
{
    T t = viewModel.BaseType;
    if (SimpleIoc.Default.IsRegistered<viewModel>() == false)
    {
        SimpleIoc.Default.Register<viewModel>();
    }
}

最佳答案

看看 SimpleIoc,我得出的结论是,没有办法做你想做的事情,因为没有 Register 方法将 Type 作为参数。

如果您考虑另一个 IoC 容器,下面是它如何与 autofac 一起工作。请注意,此示例做出了一些假设(对命名空间进行过滤,每个依赖项都有一个接口(interface)),在使用之前根据您的情况删除或更改这些假设。

    var repositoryAssembly = typeof(SettingsViewModel).Assembly;
    var registrations =
        from type in repositoryAssembly.GetExportedTypes()
        where type.Namespace == "MyApp.ViewModels"
        where type.GetInterfaces().Any()
        select new { Service = type.GetInterfaces().Single(), Implementation = type };

    foreach (var reg in registrations)
    {
        container.RegisterType(reg.Implementation).As(reg.Service).InstancePerRequest();
    }

关于c# - 如何在 MVVM Light SimpleIoc 中注册一系列依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35865962/

相关文章:

c# - 如何在没有\/Date的情况下格式化JSON日期?

c# - 提取分配给文件的正确 16x16 图标?

Java:如何创建通用 ENUM 类型

ios - 如何在 Swift 中简化几乎相等的枚举扩展

silverlight - 带有每个 Tab 的 UI Tabbed 具有不同的 View/ViewModel

xaml - UserControl 上的 MVVMLight ViewModelLocator

C# 将 XML 作为参数传递给 XSLT

java - 使用通用接口(interface)实例化枚举集合的单行代码

c# - WPF 应用程序的异步和填充数据

c# - 组合框1到2选定索引