What lifetime scope to use when using an instance in a separate thread?

Viewed 206

I have a WebApi project and in a controller I'm using HostingEnvironment.QueueBackgroundWorkItem to start a job in a separate thread:

public IHttpActionResult DoJob()
{
    HostingEnvironment.QueueBackgroundWorkItem(ct =>
    {
        var service = new MyService(logService, userInfo);
        var entity = service.DoJob(ct);
    });

    return Ok();
}

Currently, in the above I'm using a concrete instance (which I want to replace) of my service . I also use Autofac and for my services, I configured as follows:

builder.RegisterAssemblyTypes(assemblies)
    .Where(t => t.Name.EndsWith("Service"))
    .AsImplementedInterfaces()
    .InstancePerRequest();

The above registration works fine for all services when using normally within a request.

Will the above registration also work for services when run in a separate thread after the request terminates?

2 Answers

Will the above registration also work for services when run in a separate thread after the request terminates?

Yes the configuration for the registration will work.

Whatever method you call in your service may or may not work:

What this means is that if you try to resolve components that are registered as instance-per-request but there’s no current request… you’re going to get an exception..

Either one of two following cases are correct.

You might get autofac to work sometimes, because the request still exists, but sometimes won't because the request ends.

or (most likely)

the execution of QueueBackgroundWorkItem() is outside the lifetime scope so it won't work at all.

So ultimately your service should create it's own lifetime scope (IDisposable etc etc).

Dependency injection is nothing to do with thread, unless we missed to configure the dependency injection of all the accessible members of that thread at the start of the application/service.

Related