I am currently working with a WCF service that is supposed to spawn a new task to be run asynchronously on a server (there are db queries etc that need to take place). It is possible (and very likely) that the response is sent back to client before the new task is finished warranting the client to close. At this point the dependencies that were available during creation of the task will no longer be available. I am still in need of some of the dependencies in order to complete the task.
How would I want to go about making sure the dependencies required for the new task are still alive?
I included some very dumbed down code to give a basic example.
public string SubmitData(
User user, Request request)
{
History history = m_history.CreateRequest(user);
//New task which will do an import of data into the DB.
Task.Factory.StartNew( () =>
Import( user, request, history ) );
/*Return some sort of response back to user so they're not waiting for
*the long process to complete
*/
return "Response";
}
private void Import(
User user,
Request request,
History history)
{
var response = Import(
user, request, history);
m_history.Save(history, response );
}
You will need to take responsibility for disposing of the dependencies yourself. Since you are using autofac, your the simplest solution is likely to used
Owned<T>See documentation: Owned Instances
Here is roughly I would factor your code to utilize
Owned<T>, though there are lots of possibilities:Judging from your question. You may benefit from some additional reading on Autofac, lifetime, and deterministic disposal.
Instance Scope
Lifetime Primer
Deterministic Disposal
Once you more firmly understand how autofac works, you will realize your problem is actually more general. Namely, how to ensure proper disposal of shared objects used by in Tasks. In my code above, I solved the issue by not sharing the object, and making the task handle disposal.