AutoFac AsyncRunner – Fix for Autofac not working with background tasks

Inspired from here:

https://stackoverflow.com/a/33830165/249895

Usage:

    public class ServiceModule :Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            
            builder.RegisterType<AutoFac.AsyncRunner>().As<AutoFac.IAsyncRunner>().SingleInstance();
        }
    }

private AutoFac.IAsyncRunner _asyncRunner;

public Controller(AutoFac.IAsyncRunner asyncRunner)
{
	
	_asyncRunner = asyncRunner;
}

public void Function()
{
	_asyncRunner.Run<IService>((cis) =>
   {
	   try
	   {
		  //do stuff
	   }
	   catch
	   {
		   // catch stuff
		   throw;
	   }
   });
}

Class:

public class AsyncRunner : IAsyncRunner
{
	private ILifetimeScope _lifetimeScope { get; set; }

	public AsyncRunner(ILifetimeScope lifetimeScope)
	{
		//Guard.NotNull(() => lifetimeScope, lifetimeScope);
		_lifetimeScope = lifetimeScope;
	}

	public Task Run<T>(Action<T> action)
	{
		Task.Factory.StartNew(() =>
		{
			using (var lifetimeScope = _lifetimeScope.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
			{
				var service = lifetimeScope.Resolve<T>();
				action(service);
			}
		});
		return Task.FromResult(0);
	}


}

Leave a Reply

Your email address will not be published. Required fields are marked *