Register an action with Autofac to launch the application

I am using MVC with Autofac. I would like to register an action that runs once to launch the application. I would like to achieve this. eg:

public class SomeModule : IOnceRunnable
{
   private IService service;

   public SomeModule(IService service) 
   {
       this.service = service;
   }

   public void Action()
   {
      // this action would be called once on application start
   }
}

containerBuilder.RegisterOnceRunnable<SomeModule>();

Can I do this?

I know that I can use the built-in container ( var container = builder.Build();<- allow manual services), but maybe there is a more "elegant" solution like the one above.

+4
source share
1 answer

What you are looking for is Autofac's Startable Components support.

You need to implement the interface Autofac.IStartable:

public class SomeModule : Autofac.IStartable
{
   private IService service;

   public SomeModule(IService service) 
   {
       this.service = service;
   }

   public void Start()
   {
      // this action would be called once on application start
   }
}

You also need to register your type as IStartable:

builder
   .RegisterType<SomeModule>()
   .As<IStartable>()
   .SingleInstance();

Autofac , Start , .

+2

Source: https://habr.com/ru/post/1546674/


All Articles