如果没有数据,在application_startup中,我们用一些假数据为数据库播种。
为此,我们正在使用Async
存储数据的方法。伟大的。唯一的问题是,我们不确定如何执行此操作,application_startup
因为这不是异步方法。
我花了很多时间试图理解@StevenCleary的教程,而且我总是陷入僵局。我完全不理解他一贯的话:
通常,您应该使用“一直向下同步”;也就是说,不要阻塞异步代码
但是我只是不知道该怎么做,在这种情况下:(
让我们想象一下这是我正在尝试使用的代码...
protected void Application_Start()
{
var someFakeData = LoadSomeFakeData();
var documentStore = new DocumentStore();
await documentStore.InitializeAsync(someFakeData);
...
// Registers this database as a singleton.
Container.Register(documentStore);
}
然后..一些使用这个的代码documentStore
。它是通过建筑注入方式注入的...
public SomeController(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
public ViewModel GetFoos()
{
using (var session = _documentStore.OpenSession())
{
... db code goes in here ...
}
}
我不是在这里尝试做一些异步代码。我实际上正在尝试同步调用此异步方法。当然,我失去了异步等等等等的好处。但是我对此感到满意。这是启动,很高兴阻止启动。
在这种情况下,您将异步初始化共享资源。因此,我建议您要么保存Task
自身,要么引入异步包装器类型。
使用Task
:
protected void Application_Start()
{
var someFakeData = LoadSomeFakeData();
var documentStore = new DocumentStore();
var documentStoreTask = documentStore.InitializeAsync(someFakeData);
...
// Registers this database task as a singleton.
Container.Register(documentStoreTask);
}
但是,这可能太尴尬了,具体取决于Container
。在这种情况下,您可以引入一个异步包装器类型:
public sealed class DocumentStoreWrapper
{
private readonly Task<DocumentStore> _documentStore;
public DocumentStoreWrapper(Data data)
{
_documentStore = CreateDocumentStoreAsync(data);
}
private static async Task<DocumentStore> CreateDocumentStoreAsync(Data data)
{
var result = new DocumentStore();
await documentStore.InitializeAsync(data);
...
return result;
}
public Task<DocumentStore> DocumentStoreTask { get { return _documentStore; } }
}
protected void Application_Start()
{
var someFakeData = LoadSomeFakeData();
var documentStoreWrapper = new DocumentStoreWrapper(someFakeData);
...
// Registers this database wrapper as a singleton.
Container.Register(documentStoreWrapper);
}
或者,您可以使用AsyncLazy<T>
,其功能大致相同,但使用后台线程执行初始化代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句