I create a Task which calls a method on a DI resolved service instance:
using(var scope = container.BeginLifetimeScope())
{
var serviceInstance = scope.Resolve<IService>(serviceType);
return Task.Factory.StartNew(serviceInstance.DoTheWork());
}
Of course this is no good: as soon as the using-block is left, all the created dependencies living on the scope are disposed of - the call to "DoTheWork()" is not yet finished and still using the injected resources.
This is not what I want. My solution for now would be this:
var scope = container.BeginLifetimeScope();
var serviceInstance = scope.Resolve<IService>(serviceType);
var task = Task.Factory.StartNew(serviceInstance.DoTheWork());
task.ContinueWith(t => { scope.Dispose(); });
The question is: Is this safe or are there cases where the continuation is simply not called for whatever reason?