使用ModernUI + Caliburn.Micro组合重新实现WindowManager

在这里, Caliburn.Micro成功地与ModernUI合并。 但是如果我们想要使用多个窗口,我们还需要重新实现Caliburn的WindowManager才能与ModernUI一起正常工作。 怎么做到呢?

更新:(关于IoC容器/dependency injection的附加问题)

好吧,我得到它:我在这里使用了一个构造函数注入:

 public class BuildingsViewModel : Conductor { public BuildingsViewModel(IWindowManager _windowManager) { windowManager = _windowManager; } } 

至于BuildingsViewModel从IoC容器解析,容器本身注入了IWindowManager接口的ModernWindowManager实现,因为BootstrapperConfigure()方法中的这一行:

 container.Singleton(); 

如果我从容器中解析对象实例,它会注入所有必需的依赖项。 像一棵树。

1)所以现在我想知道如何使用注射(带接口)替换这条线? _windowManager.ShowWindow(new PopupViewModel());

2)如果我希望我的整个项目匹配DI模式,所有对象实例必须注入ModernWindowViewModel ,它首先从容器解析?

3)在整个项目中使用Caliburn的SimpleContainer是否可以,或者更好地使用像Castle Windsor这样的成熟框架? 我应该避免混合吗?

UPDATE2:

4)将IoC容器集成到现有应用程序中需要首先创建此容器(例如,在控制台应用程序的Main()方法中),然后所有对象实例必须通过注入的依赖项从中增长?

只需创建自己的派生WindowManager并覆盖EnsureWindow

 public class ModernWindowManager : WindowManager { protected override Window EnsureWindow(object rootModel, object view, bool isDialog) { var window = view as ModernWindow; if (window == null) { window = new ModernWindow(); window.SetValue(View.IsGeneratedProperty, true); } return window; } } 

您要用作弹出窗口的任何视图都必须基于ModernWindow并且必须使用LinkGroupCollection或者必须设置窗口的ContentSource属性,否则将不会有内容。

您可以使用View-First但它使用上面的方法运行ViewModel-First

例如,为了弹出我的PopupView我做了以下操作

PopupView.xaml

   

PopupViewModel.cs

 public class PopupViewModel : Screen { // Blah } 

用于从另一个ViewModel弹出视图的代码:

 public void SomeMethod() { _windowManager.ShowWindow(new PopupViewModel()); // Or use injection etc } 

不要忘记在容器中注册ModernWindowManager来代替WindowManager

例如,使用CM的SimpleContainer

 container.Singleton(); 

显然,我能看到的唯一缺点就是你似乎无法将内容直接放在ModernWindow ,所以你必须为每个弹出窗口都有两个UserControls

解决方法是在EnsureWindow中更改EnsureWindow ,以便它基于ModernWindow创建UserControl并将ContentSource设置为要加载的视图的URI,这将触发内容加载器并连接ViewModel 。 如果我有一分钟尝试,我会更新。

更新:

好的,所以目前它非常hacky,但这可能是一些有用的东西的起点。 基本上我是基于命名空间和视图名称生成URI。

我确信有一种更可靠的方法可以做到这一点,但对于我的测试项目,它可以工作:

 protected override Window EnsureWindow(object rootModel, object view, bool isDialog) { var window = view as ModernWindow; if (window == null) { window = new ModernWindow(); // Get the namespace of the view control var t = view.GetType(); var ns = t.Namespace; // Subtract the project namespace from the start of the full namespace ns = ns.Remove(0, 12); // Replace the dots with slashes and add the view name and .xaml ns = ns.Replace(".", "/") + "/" + t.Name + ".xaml"; // Set the content source to the Uri you've made window.ContentSource = new Uri(ns, UriKind.Relative); window.SetValue(View.IsGeneratedProperty, true); } return window; } 

我的视图的完整命名空间是TestModernUI.ViewModels.PopupView ,生成的URI是/ViewModels/PopupView.xaml ,然后通过内容加载器自动加载和绑定。

更新2

这里是我的Bootstrapper配置方法:

 protected override void Configure() { container = new SimpleContainer(); container.Singleton(); container.Singleton(); container.PerRequest(); container.PerRequest(); container.PerRequest(); } 

在这里,我创建容器,并注册一些类型。

诸如WindowManagerEventAggregator类的CM服务都是针对它们各自的接口和单例进行注册的,因此在运行时只有1个实例可用。

视图模型注册为PerRequest ,每次从容器中请求时都会创建一个新实例 – 这样您就可以多次弹出相同的窗口而不会出现奇怪的行为!

这些依赖项将注入到运行时解析的任何对象的构造函数中。

更新3

在回答您的IoC问题时:

1) So now I wonder how can I replace this line using an injection(with interface)? _windowManager.ShowWindow(new PopupViewModel());

由于您的viewmodels现在通常需要依赖项,因此您需要有一些方法将它们注入实例。 如果PopupViewModel有多个依赖项,您可以将它们注入到父类中,但这会以某种方式将父视图模型耦合到PopupViewModel

您可以使用其他几种方法来获取PopupViewModel的实例。

注入它!

如果您将PopupViewModel注册为PerRequest ,则每次请求时都会获得它的新实例。 如果在viewmodel中只需要一个弹出窗口实例,则可以将其注入:

 public class MyViewModel { private PopupViewModel _popup; private IWindowManager _windowManager; public MyViewModel(PopupViewModel popup, IWindowManager windowManager) { _popup = popup; _windowManager = windowManager; } public void ShowPopup() { _windowManager.ShowPopup(_popup); } } 

唯一的缺点是,如果你需要在同一个视图模型中多次使用它,那么实例将是同一个实例,但是如果你知道你需要多少同时PopupViewModel实例

使用某种forms的按需注射

对于以后需要的依赖项,您可以使用按需注入,例如工厂

我不认为Caliburn或SimpleContainer支持工厂开箱即用,所以替代方案是使用IoC.GetIoC是一个静态类,允许您在实例化后访问DI容器

  public void ShowPopup() { var popup = IoC.Get(); _windowManager.ShowWindow(popup); } 

您需要确保在引导程序中正确注册了容器,并将对CM的IoC方法的任何调用委托给容器 – IoC.Get调用引导程序的GetInstance和其他方法:

这是一个例子:

 public class AppBootstrapper : BootstrapperBase { SimpleContainer container; public AppBootstrapper() { Initialize(); } protected override void Configure() { container = new SimpleContainer(); container.Singleton(); container.Singleton(); container.PerRequest(); // Register viewmodels etc here.... } // IoC.Get or IoC.GetInstance(Type type, string key) .... protected override object GetInstance(Type service, string key) { var instance = container.GetInstance(service, key); if (instance != null) return instance; throw new InvalidOperationException("Could not locate any instances."); } // IoC.GetAll or IoC.GetAllInstances(Type type) .... protected override IEnumerable GetAllInstances(Type service) { return container.GetAllInstances(service); } // IoC.BuildUp(object obj) .... protected override void BuildUp(object instance) { container.BuildUp(instance); } protected override void OnStartup(object sender, System.Windows.StartupEventArgs e) { DisplayRootViewFor(); } 

Castle.Windsor支持工厂,以便您可以更明确地ResolveRelease组件并管理其生命周期,但我不会在此处讨论

2) If I want my whole project match DI pattern, all objects instances must be injected into ModernWindowViewModel, that resolves from container first?

您只需要注入ModernWindowViewModel所需的依赖ModernWindowViewModel 。 儿童需要的任何东西都会自动解决并注入,例如:

 public class ParentViewModel { private ChildViewModel _child; public ParentViewModel(ChildViewModel child) { _child = child; } } public class ChildViewModel { private IWindowManager _windowManager; private IEventAggregator _eventAggregator; public ChildViewModel(IWindowManager windowManager, IEventAggregator eventAggregator) { _windowManager = windowManager; _eventAggregator = eventAggregator; } } 

在上面的情况下,如果您从容器中解析ParentViewModelChildViewModel将获得它的所有依赖项。 您不需要将它们注入父级。

3) Is it okay to use Caliburn's SimpleContainer for whole project, or better use mature framework like Castle Windsor? Should I avoid mixing?

你可以混合,但它可能会让人感到困惑,因为它们不能相互协作(一个容器不会知道另一个容器)。 只需坚持使用一个容器, SimpleContainer就可以了 – Castle Windsor有很多function,但你可能永远不需要它们(我只使用了一些高级function)

4) Integrating an IoC container into an existing application requires creating this container first(in Main() method of console app for example), and then all object instanses must grow from it with injected dependencies?

是的,您创建容器,然后解析根组件(99.9%的应用程序中有一个主组件称为组合根),然后构建完整的树。

以下是基于服务的应用程序的引导程序示例。 我正在使用Castle Windsor,我希望能够在Windows服务或WPF应用程序中或甚至在控制台窗口(用于测试/调试)中托管引擎:

 // The bootstrapper sets up the container/engine etc public class Bootstrapper { // Castle Windsor Container private readonly IWindsorContainer _container; // Service for writing to logs private readonly ILogService _logService; // Bootstrap the service public Bootstrapper() { _container = new WindsorContainer(); // Some Castle Windsor features: // Add a subresolver for collections, we want all queues to be resolved generically _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel)); // Add the typed factory facility and wcf facility _container.AddFacility(); _container.AddFacility(); // Winsor uses Installers for registering components // Install the core dependencies _container.Install(FromAssembly.This()); // Windsor supports plugins by looking in directories for assemblies which is a nice feature - I use that here: // Install any plugins from the plugins directory _container.Install(FromAssembly.InDirectory(new AssemblyFilter("plugins", "*.dll"))); _logService = _container.Resolve(); } ///  /// Gets the engine instance after initialisation or returns null if initialisation failed ///  /// The active engine instance public IIntegrationEngine GetEngine() { try { return _container.Resolve(); } catch (Exception ex) { _logService.Fatal(new Exception("The engine failed to initialise", ex)); } return null; } // Get an instance of the container (for debugging) public IWindsorContainer GetContainer() { return _container; } } 

一旦创建了引导程序,它就会设置容器并注册所有服务以及插件dll。 对GetEngine的调用通过从容器中解析Engine来启动应用程序,该容器创建完整的依赖关系树。

我这样做是为了让它能够像这样创建应用程序的服务或控制台版本:

服务代码:

 public partial class IntegrationService : ServiceBase { private readonly Bootstrapper _bootstrapper; private IIntegrationEngine _engine; public IntegrationService() { InitializeComponent(); _bootstrapper = new Bootstrapper(); } protected override void OnStart(string[] args) { // Resolve the engine which resolves all dependencies _engine = _bootstrapper.GetEngine(); if (_engine == null) Stop(); else _engine.Start(); } protected override void OnStop() { if (_engine != null) _engine.Stop(); } } 

控制台应用:

 public class ConsoleAppExample { private readonly Bootstrapper _bootstrapper; private IIntegrationEngine _engine; public ConsoleAppExample() { _bootstrapper = new Bootstrapper(); // Resolve the engine which resolves all dependencies _engine = _bootstrapper.GetEngine(); _engine.Start(); } } 

这是IIntegrationEngine实现的一部分

 public class IntegrationEngine : IIntegrationEngine { private readonly IScheduler _scheduler; private readonly ICommsService _commsService; private readonly IEngineStateService _engineState; private readonly IEnumerable _components; private readonly ConfigurationManager _configurationManager; private readonly ILogService _logService; public IntegrationEngine(ICommsService commsService, IEngineStateService engineState, IEnumerable components, ConfigurationManager configurationManager, ILogService logService) { _commsService = commsService; _engineState = engineState; _components = components; _configurationManager = configurationManager; _logService = logService; // The comms service needs to be running all the time, so start that up commsService.Start(); } 

所有其他组件都有依赖项,但我没有将它们注入IntegrationEngine – 它们由容器处理