In the past I have used AutoFac to inject a EntityFramework DB context to various services on a InstancePerRequest schedule.
builder.RegisterType<MyDataContext>()
.As<IDataContext>()
.As<IUnitOfWork>()
.InstancePerRequest();
This has allowed me to share the context across services when injecting multiple services into a controller.
// Note each of these services take a IDataContext via constructor injection
public FilesController(
IAnalysisService analysisService,
IUserService userService)
{
}
I have an action filter that commits my Context at the end of each action request (I am probably looking at changing this but for now it suites my purpose of this question).
public class UnitOfWorkActionAttribute : ActionFilterAttribute
{
public IUnitOfWork UnitOfWork { get; set; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
UnitOfWork.SaveChangesAsync().WaitAndUnwrapException();
}
}
My reading of async in MVC is that the thread that started the request is not guaranteed to finish it due to it being freed up when using await
.
In AutoFac injection does this mean that the UnitOfWork instance injected into the ActionFilterAttribute might differ from the one injected into the Controller or is InstancePerRequest not effected by changes to the Thread handling the request?