My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Startable  
Autofac provides the IStartable interface for components that need to be notified when the container is built
Autofac2
Updated Mar 20, 2011 by nicholas...@gmail.com

Important Note: The earlier package AutofacContrib.Startable.dll is now obsolete and has been replaced with the implementation in Autofac.dll.

A startable component is one that is activated by the container when the container is initially built.

Step 1: Implement IStartable

Startable components must implement IStartable.Start().

class StartupMessageWriter : IStartable
{
   public void Start()
   {
      Console.WriteLine("App is starting up!");
   }
}

Step 2: Register the component with ContainerBuilder

Startable components are just regular components, that can be registered in the usual way and can take constructor dependencies as needed.

var builder = new ContainerBuilder();
builder.RegisterType<StartupMessageWriter>()
   .As<IStartable>()
   .SingleInstance();

Step 3: Build the container

When the container is built, Autofac will create an instance of each startable component and call its start method.

var container = builder.Build();
// Message will appear on console.

This only happens once, for a single instance of each component, the first time the container is built. Resolving startable components by hand won't result in their Start() method being called. It isn't recommended that startable components implement other services, or have non-SingleInstance() lifetimes.

Components that need to have something like a Start() method called each time they are activated should use the usual OnActivated() event handlers instead.

Comment by christin...@gmail.com, Aug 22, 2011

"The earlier package AutofacContrib?.Startable.dll is now obsolete and has been replaced with the implementation in Autofac.dll. " I would like to know where the old "StartableModule?" class in

Thanks

Comment by project member nicholas...@gmail.com, Aug 24, 2011

Hi, there's no longer any StartableModule class, as the functionality is provided by default. Just leave the code registering the module out, and follow the instructions above. Cheers!


Sign in to add a comment
Powered by Google Project Hosting