【问题标题】:UWP Mvvm Prism ConfirgureContainer IssueUWP Mvvm Prism 配置容器问题
【发布时间】:2019-04-09 19:36:44
【问题描述】:

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

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

我添加了 async 关键字,因为我想初始化一些在 ConfigureContainer() 中等待的数据库连接。但是现在我注意到应用程序启动(有时)没有启动 ags 被 instatiated 导致 null ref 异常。我不应该在这种方法中初始化任何连接吗?为什么应用程序不在 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);
    }

【问题讨论】:

    标签: uwp prism


    【解决方案1】:

    我不应该在这个方法中初始化任何连接吗?

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

    为什么应用没有在 ConfigureContainer() 上等待?

    因为不能awaitvoid。这就是不鼓励使用async void 的原因...async Task 中的Taskawaited,而不是async

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

    没有async 构造函数或async new 这样的东西。 this post by Stephen Cleary.

    Container.RegisterInstance&lt;IResourceLoader&gt;(new ResourceLoaderAdapter(new ResourceLoader()));

    注册实例是丑陋的,而且大多数时候是不必要的(这是一个例子)。如果你重构你的代码让容器完成它的工作,你的异步初始化问题就会消失。

    【讨论】:

      【解决方案2】:

      不要把你的初始化代码放进去

       protected override  void ConfigureContainer()
      

      把它放进去:

       protected override async Task OnInitializeAsync(IActivatedEventArgs args)
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 2011-10-06
        相关资源
        最近更新 更多