UWP Mvvm Prism Confirgure容器问题

时间:2018-11-06 11:55:19

标签: uwp prism

我在UWP应用中使用Prism。我正在

中为每个View模型注册一些启动参数。
    protected override async void ConfigureContainer()

我添加了async关键字,因为我想初始化一些可在ConfigureContainer()中等待的数据库连接。但是,现在我注意到该应用程序启动(有时)时,启动ags被无效,导致空引用异常。我不应该用这种方法初始化任何连接吗?为什么应用程序没有在ConfigureContainer()上等待?应用启动时,我应该在哪里放置异步初始化方法调用?这是方法。

 protected override async void ConfigureContainer()
    {


        // register a singleton using Container.RegisterType<IInterface, Type>(new ContainerControlledLifetimeManager());
        base.ConfigureContainer();
        Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader()));
        DocumentClient client = new DocumentClient(new Uri("https://docdb.etc/"),
             "my key", new ConnectionPolicy() { ConnectionMode = ConnectionMode.Direct });
        try
        {
            await client.OpenAsync();
        }
        catch (Exception ex)
        {

            throw new Exception("DocumentClient client could not open");
        }
        IDataAccessBM _db = new DataAccessDocDb(client, "ct", "ops");
        AddressSearch addresSearcher = new AddressSearch(_db, 4);
        StartUpArgs startUpArgs = new StartUpArgs
        {
            postCodeApiKey = "anotherKey",
            db = _db,
            fid = "bridge cars",
            dialogService = new DialogService(),
            addressSearcher = addresSearcher
        };
        startUpArgs.zoneSet = await _db.ZoneSetGetActiveAsync("another key");
        Container.RegisterInstance(startUpArgs);
    }

2 个答案:

答案 0 :(得分:1)

  

我不应该用这种方法初始化任何连接吗?

至少不是异步的。我宁愿创建一个ConnectionFactory来(可能是异步地)按需创建连接。

  

为什么应用程序不等待ConfigureContainer()?

因为一个人不能await void。这是不鼓励使用async void的原因……是Taskasync Task中的await,而不是async

  

应用启动时,我应该在哪里放置异步初始化方法调用?

没有async构造函数或async new这样的东西。 this post by Stephen Cleary是探索您的选择的一个良好开端。

  

Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader()));

注册实例很丑陋,并且在大多数情况下是不必要的(这是一个示例)。如果您重构代码以让容器完成其工作,则async-initialization-problem问题将消失。

答案 1 :(得分:0)

请勿将初始化代码放入

 protected override  void ConfigureContainer()

放入:

 protected override async Task OnInitializeAsync(IActivatedEventArgs args)

可以从那里访问容器,并且该方法是异步的。