使用 Caliburn Micro 的简单注入器 GetAllInstances 抛出异常

Simple Injector GetAllInstances throwing exception with Caliburn Micro

我曾从事 Simple Injector 和 Caliburn micro 但已经有将近 2 年的时间了。今天,当我尝试创建一个简单的 WPF 应用程序时。首先,我最终阅读了文档,因为两个库都进行了大量更改。

我 运行 遇到了一些问题,例如 "view can not be found" ,这些问题后来得到了解决,但现在我遇到了一个 st运行ge 问题。已尝试启用记录器和所有功能,但不知道是 Caliburn micro 还是简单注入器的问题。

这是我的引导程序 class:

 internal class AppBootstrapper : BootstrapperBase
    {
        public static readonly Container ContainerInstance = new Container();

        public AppBootstrapper()
        {
            LogManager.GetLog = type => new DebugLogger(type);
            Initialize();
        }

        protected override void Configure()
        {
            ContainerInstance.Register<IWindowManager, WindowManager>();
            ContainerInstance.RegisterSingleton<IEventAggregator, EventAggregator>();

            ContainerInstance.Register<MainWindowViewModel, MainWindowViewModel>();

            ContainerInstance.Verify();
        }

        protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
        {
            DisplayRootViewFor<MainWindowViewModel>();
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            // This line throwing is exception when running the application
            // Error: 
            // ---> An exception of type 'SimpleInjector.ActivationException' occurred in SimpleInjector.dll
            // ---> Additional information: No registration for type IEnumerable<MainWindowView> could be found. 
            // ---> No registration for type IEnumerable<MainWindowView> could be found. 
            return ContainerInstance.GetAllInstances(service);
        }

        protected override object GetInstance(System.Type service, string key)
        {
            return ContainerInstance.GetInstance(service);
        }

        protected override IEnumerable<Assembly> SelectAssemblies()
        {
            return new[] {
                    Assembly.GetExecutingAssembly()
                };
        }

        protected override void BuildUp(object instance)
        {
            var registration = ContainerInstance.GetRegistration(instance.GetType(), true);
            registration.Registration.InitializeInstance(instance);
        }
    }

不确定我在这里遗漏了什么?

Simple Injector v3 包含多项重大更改。困扰你的是issue #98的breaking change。默认情况下,Simple Injector v3 不会再将未注册的集合解析为空集合。正如您所注意到的,这会破坏 Caliburn 的适配器。

要解决此问题,您必须将 GetAllInstances 方法更改为以下内容:

protected override IEnumerable<object> GetAllInstances(Type service)
{
    IServiceProvider provider = ContainerInstance;
    Type collectionType = typeof(IEnumerable<>).MakeGenericType(service);
    var services = (IEnumerable<object>)provider.GetService(collectionType);
    return services ?? Enumerable.Empty<object>();
}