Prism.Autofac.WPF 7 - 无法解析IContainer

时间:2018-01-24 15:13:25

标签: c# wpf prism autofac

我在这里有点失落。我正在尝试用Prism.Autofac.Wpf 7建立一个非常简单的应用程序;

App.xaml.cs:

>>> calcsize("hl")     # Defaults to native "natural" alignment padding
16
>>> calcsize("hl", 1)  # pack=1 means no alignment padding between members
10

的App.xaml:

public partial class App
{
    protected override Window CreateShell()
    {
        return Container.Resolve<MainWindow>(); // this point won't even be reached
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
    }

    protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
    {
        base.ConfigureModuleCatalog(moduleCatalog);
    }
}

启动时,这会在调用RegisterTypes()之后但在调用CreateShell()之前的某个时刻抛出DependencyResolutionException:

<prism:PrismApplication x:Class="MyNamespace.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:prism="http://prismlibrary.com/"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</prism:PrismApplication>

天真地走错误信息并尝试自己注册IContainer,我试过了

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type   'Prism.Autofac.AutofacServiceLocatorAdapter' can be invoked with the available services and parameters:
Cannot resolve parameter 'Autofac.IContainer container' of constructor 'Void .ctor(Autofac.IContainer)'.

at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)

然后我会得到一个InvalidOperationException:“Build()或Update()只能在ContainerBuilder上调用一次。”

我在这里有点迷失 - 这个最小的例子出了什么问题?!

由于

2 个答案:

答案 0 :(得分:0)

WPF还没有Prism v7。因此,您必须使用CI构建,或者可能使用预览。话虽如此,您无法致电Build()。当应用程序的初始化完成时,Prism会调用它。 Autofac是一个不可变的容器,这意味着一旦你调用Build(),你就不能再用容器注册任何内容了。

答案 1 :(得分:0)

首先自己构建容器会导致坏事。同样由于Autofac弃用Builder.Update,我们现在确保您拥有Prism在幕后使用的相同构建器。当您调用builder.Build()时,您无法在ContainerRegistry中注册生成的IContainer,因为您构建了构建器......由于弃用,第二个Autofac是不可变的,这就是我们不再支持模块的原因Autofac。

使用新的Prism 7 IOC接口,您应该尝试注入IContainerProvider。这将允许你解决你需要的东西....假设在这里你有充分的理由这样做....

最后,我应该指出Autofac故意不解决IContainer,如果由于某种原因需要Autofac特定接口,则应该解析IComponentContextILifetimeScope。您可以阅读有关here的更多信息。

相关问题