C# WPF Caliburn.Micro之动态注入

概述

     在Caliburn.Micro中,我们一般在引导程序中实例化SimpleContainer,然后在Configure中去注入我们的实例,那如果我不想在一开始就注入所有实例,我想在其他类模块去实现动态注入,怎么去实现呢?这节就这个场景通过实例展开讲解.

实例

    首先是继承引导程序类并重写我们实现IOC容器需要用到的几个方法.

    public class HelloBootstrapper : BootstrapperBase    {        public HelloBootstrapper()        {            Initialize();        }        protected override void OnStartup(object sender, StartupEventArgs e)        {            //DisplayRootViewFor<MainWindowViewModel>();            DisplayRootViewFor<ILogin>();        }        private SimpleContainer container;        protected override void Configure()        {            container = new SimpleContainer();             container.Singleton<SimpleContainer>();              }        protected override object GetInstance(Type service, string key)        {            return container.GetInstance(service, key);        }        protected override IEnumerable<object> GetAllInstances(Type service)        {            return container.GetAllInstances(service);        }        protected override void BuildUp(object instance)        {            container.BuildUp(instance);        }        #region        protected override IEnumerable<Assembly> SelectAssemblies()        {            return new[] { Assembly.GetExecutingAssembly() };        }        #endregion    }

在这里我们注入 容器本身

container.Singleton<SimpleContainer>();

在我们需要注入实例的获取ioc容器:

 var subContainer = IoC.Get<SimpleContainer>();

然后通过Singleton去注入实例,CreateChildContainer方法可以在容器中生成子容器

    subContainer.Singleton<IViewModel, ShellViewModel>();            subContainer.Singleton<IViewModel, EventAggregatorViewModel>();            var subsubContainer = subContainer.CreateChildContainer();            subsubContainer.Singleton<IViewModel, ShellViewModel>();            subsubContainer.Singleton<IViewModel, EventAggregatorViewModel>();

通过GetAllInstances可以获取注入的所有实例。

注入实例代码如下:

  public void IocTest1()        {                  subContainer.Singleton<IViewModel, ShellViewModel>();            subContainer.Singleton<IViewModel, EventAggregatorViewModel>();            var subsubContainer = subContainer.CreateChildContainer();            subsubContainer.Singleton<IViewModel, ShellViewModel>();            subsubContainer.Singleton<IViewModel, EventAggregatorViewModel>();        }
        public void IocTest2()        {            var count = subContainer.GetAllInstances<IViewModel>().Count();            MessageBox.Show($"总共实例数量:{count}");
            var shellVM = subContainer.GetAllInstances<IViewModel>().                FirstOrDefault(vm => vm.GetType() == typeof(ShellViewModel));            ((ShellViewModel)shellVM).AddData();        }
        public void IocTest3()        {            var shellVM = IoC.Get<SimpleContainer>().GetAllInstances<IViewModel>().                FirstOrDefault(vm => vm.GetType() == typeof(ShellViewModel));            ((ShellViewModel)shellVM).ShowNewWindow();        }

运行演示:

C# WPF Caliburn.Micro之动态注入