简体   繁体   中英

Autofac heavy Initialize task

Is there a way with Autofac DI to add an initialize method that will run on a different thread for a registered component?

Instead of having this:

public class Service
{
   public Service()
   { 
      // Heavy init task
   }
}

Have this:

public class Service
{
   public Service()
   { 
      // No logic
   }

   // This should run on different thread when Service is created
   public void Init()
   {
      // Heavy init 
   }
}

You can register using a lambda expressions, in which you can add code. Then you can start a task that calls the init-method.

Something like this:

builder.Register(c => {
    var instance = new Service();
    new Task(() => instance.Init()).Start();
    return instance;
}).As<IService>().SingleInstance();

I guess not. The problem is that Autofac is probably needed to initialize everything comes after the service startup: repository, engines, and so on. What about if you need a component to continue the service work but Autofac is still in the middle of the initialization process? You have to stop processing the service, wait for Autofac to continue, and then start the process again... well, it's like a normal startup process.

One possible options is to user the Autofac IStartable components. Check this answer for more details.

You can for example immediately load everything you need for the "service" startup, and demand to the startable section everything is not immediately required (a kind of lazy loading). Then you can do something like this:

var newBuilder = new ContainerBuilder();
newBuilder.Register...;

newBuilder.Update(existingContainer);

to update the container with the other components.

Hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM