我在一个UWP应用程序中使用Prism。中的每个视图模型都注册了一些启动args
protected override async void ConfigureContainer()
我添加了异步关键字,因为我想初始化一些数据库连接,这些连接在ConfigureContainer()中是可使用的。但现在我注意到,应用程序启动(有时)时,启动时会对启动ags进行安装,从而导致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);
}
发布于 2018-11-06 05:52:31
不要将初始化代码放入
protected override void ConfigureContainer()
放进去:
protected override async Task OnInitializeAsync(IActivatedEventArgs args)
容器可以从那里访问,并且方法是异步的。
发布于 2018-11-06 05:41:49
我不应该在这个方法中初始化任何连接吗?
至少不是异步的。我宁愿创建一个(可能是异步的)按需创建连接的ConnectionFactory
。
为什么应用程序不等待ConfigureContainer()?
因为一个人不能await
void
。这就是为什么不鼓励使用async void
.Task
in async Task
才是await
ed,而不是async
。
当应用程序启动时,我应该将异步初始化方法调用放在哪里?
没有像async
构造函数或async new
这样的东西。在这里探索您的选择的一个良好开端是这篇文章是斯蒂芬·克利里写的。
Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader()));
注册实例是丑陋的,而且大多数情况下都是不必要的(这就是一个例子)。如果您重构代码以让容器完成其工作,异步初始化问题就会消失。
https://stackoverflow.com/questions/53171411
复制相似问题