這種類型的問題的一般解決方案是在代理實現後隱藏如此重的對象。這樣,您可以在應用程序啓動時直接觸發初始化過程,而操作在後臺運行,而不會阻止請求(除非它們在請求期間需要未初始化的數據)。
如果您的代碼如下所示:
// The abstraction in question
public interface IMyService
{
ServiceData GetData();
}
// The heavy implementation
public class HeavyInitializationService : IMyServic {
public HeavyInitializationService() {
// Load data here
Thread.Sleep(3000);
}
public ServiceData GetData() => ...
}
代理可以如下創建:
Lazy<IMyService> lazyService = new Lazy<IMyService>(() =>
new HeavyInitializationService());
container.Register<IMyService>(c => new LazyMyServiceProxy(lazyService))
.SingleInstance();
// Trigger the creation of the heavy data on a background thread:
Task.Factory.StartNew(() => {
// Triggers the creation of HeavyInitializationService on background thread.
var v = lazyService.Value;
});
這就是:
如下您可以使用此代理可能是一個更好的解決方案,因爲它有些繞過了長時間的應用程序啓動時間,否則你可能會得到,但你也可以[使用Autofac的'IStartable'或'AutoActivate'支持](http://autofac.readthedocs.io/en/latest/lifetime/startup.html)。你可以在這裏結合後臺初始化策略來做到這一點。 –