CaliburnMicroConstructorInjectionFailed我正在学习CaliburnMicro,尝试使用官网的EventAggregator。但是,我得到一个异常“没有为此对象定义无参数构造函数。”消息本身很清楚,但该示例也不包含无参数构造函数。如果我添加一个,则不会命中带参数的构造函数,并且IEventAggregator仍未正确注入。添加无参数构造函数后,这是我的发布者VM(没有它,将抛出异常):publicMainViewModel(){}publicMainViewModel(IEventAggregatorea):this(){eventAggregator=ea;这是我正在做的事情Bootstrapper使用:publicclassAppBootstrapper:Bootstrapper{protectedoverridevoidConfigure(){container.Singleton();这是CM示例://CreatingtheEventAggregatorasasingleton。公共类Bootstrapper:BootstrapperBase{privatereadonlySimpleContainer_container=newSimpleContainer();//...其他BootstrapperConfigprotectedoverridevoidConfigure(){_container.单例();}//...其他引导程序配置}//在vi??ewModel中获取EventAggregator。公共类FooViewModel{私有只读IEventAggregator_eventAggregator;publicFooViewModel(IEventAggregatoreventAggregator){_eventAggregator=eventAggregator;}}我查了这篇文章(InjectingEventAggregatorintoViewModelwithCaliburnMicro,不过很简单)CM没有理由不通过注入调用构造函数。我还检查了CM的示例解决方案,但它使用MEF作为DI解决方案。我错过了什么?//...OtherBootstrapperConfig这是另一个重要的引导程序配置。最好的办法是通过Caliburn.Micro.StartNuGet包安装Caliburn.Micro,然后查看提供的引导程序,它也使用Caliburn.Micro提供的SimpleContainer。到这里就完成了:publicclassAppBootstrapper:BootstrapperBase{SimpleContainercontainer;公共AppBootstrapper(){开始();}protectedoverridevoidConfigure(){container=newSimpleContainer();container.Singleton();container.Singleton();容器.PerRequest();}protectedoverrideobjectGetInstance(Typeservice,stringkey){varinstance=container.GetInstance(service,key);如果(实例!=null)返回实例;thrownewInvalidOperationException("找不到任何实例。");}protectedoverrideIEnumerableGetAllInstances(Typeservice){returncontainer.GetAllInstances(service);}protectedoverridevoidBuildUp(objectinstance){container.BuildUp(instance);}protectedoverridevoidOnStartup(objectsender,System.Windows.StartupEventArgse){DisplayRootViewFor();}}devdigital是对的。他说这是另一个重要的引导程序配置。这是绝对正确的。如果您计划使用DI(SimpleContainer为您做的),那么您必须在引导程序中重写GetInstance()、GetAllInstances()、BuildUp()方法,因为CM在需要容器中的内容时调用这些方法。您的情况是这样的:CM尝试显示您的MainViewModel,因为您在Bootstrapper中将其指定为泛型参数。CM注意到您的MainViewModel有一个带有IEventAggregator的构造函数。CM调用GetInstance()以获取注册为IEventAggregators的任何IEventAggregators。CM发现您没有覆盖GetInstance(),因此它尝试使用Activator.CreateInstance()创建MainViewModel的实例。Activator.CreateInstance()不知道如何创建IEventAggregator所以它抛出一个异常(你得到的那个)。要解决所有这些问题,您必须重写我告诉您的方法。您不需要安装NugetCaliburn.Start包(如果您不喜欢打字并希望节省一些击键次数,则可以使用它)。基本上你最终的解决方案应该是这样的:以上就是C#学习教程的全部内容:CaliburnMicro构造函数注入失败分享,如果对你有用,需要进一步了解C#学习教程,希望大家付费更多关注—publicclassBootstrapper:Bootstrapper{privatereadonlySimpleContainer_container=newSimpleContainer();protectedoverridevoidConfigure(){_container.Instance(newWindowManager());_container.Singleton();_container.PerRequest();(类型服务,字符串键){return_container.GetInstance(服务,键);}protectedoverrideIEnumerableGetAllInstances(Typeservice){return_container.GetAllInstances(service);}protectedoverridevoidBuildUp(objectinstance){_container.BuildUp(instance);}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
