我想在我的 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/