简单的Injector GetAllInstances用Caliburn Micro抛出异常

时间:2015-08-27 20:29:40

标签: c# wpf caliburn.micro simple-injector

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

我遇到了一些问题,例如“查看无法找到”,后来得到解决,但现在我遇到了一个奇怪的问题。尝试启用记录器和一切,但不知道它是Caliburn micro或简单喷射器的问题。

这是我的bootstrapper类:

 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);
        }
    }

不确定我在这里缺少什么?

1 个答案:

答案 0 :(得分:8)

Simple Injector v3包含几个重大更改。你所困扰的是issue #98的突然变化。默认情况下,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>();
}