I'm trying to make this code working:
protected async Task RunIsolated<TServ1, TServ2>(Action<TServ1, TServ2> action)
{
await RunInScope(action, typeof(TServ1), typeof(TServ2));
}
protected async Task<TResult> RunIsolatedForResult<TService, TResult>(Func<TService, TResult> func)
{
return (TResult) await RunInScope(func, typeof(TService));
}
private Task<object> RunInScope(Delegate d, params object[] args)
{
using (var scope = _serviceProvider.CreateScope())
{
object[] parameters = args.Cast<Type>().Select(t => scope.ServiceProvider.GetService(t)).ToArray();
return Task.FromResult(d.DynamicInvoke(parameters));
}
}
this work for sync version of code, like this:
await RunIsolated<Service>(serv => serv.SaveAsync(item).Wait());
but don't work (db operation throw an exception) for async version of the same code
await RunIsolated<Service>(async serv => await serv.SaveAsync(item));
Is it somehow possible to convert async Action
or Func
to Delegate
and invoke it without loosing async state?