Litium application lifecycle

Litium application lifecycle events.

Application lifetime

Litium application lifecycle events can be used to execute code that depend on different states in the application. The application lifecycle events exist in Litium.Runtime.IApplicationLifetime and are using constructor injection in your class implementation.

using Litium.Runtime;

namespace Litium.Application.Examples
{
    [Autostart]
    public class ApplicationLifecycleExample
    {
        public ApplicationLifecycleExample(IApplicationLifetime applicationLifetime)
        {
            applicationLifetime.ApplicationStarted.Register(() =>
            {
                // Code that should be executed when the application have executed all steps for application to start.
                // Services that are injected in constructor can be used.
            });
            applicationLifetime.ApplicationStopping.Register(() =>
            {
                // Code that should be executed when the application is notified that it should shut down.
                // Services that are injected in constructor can be used.
            });
            applicationLifetime.ApplicationStopped.Register(() =>
            {
                // Code that should be executed when the application is stopped
                // this is the last event before application container is terminating.
                // Avoid to use services that are injected in constructor, 
                // they could already have stopped and will not respond correctly.
            });
        }
    }
}

Auto start

A class can be initialized during the application startup process. An example would be that a class should run in the background and listen for events or process a service bus queue.

To make a class instantiate during application initialisation it should be decorated with the Litium.Runtime.Autostart attribute. The implementation class can use other services registered in the dependency injection with constructor injection, but the implementation does not need to be registered in the dependency injection.

using Litium.Events;
using Litium.Runtime;

namespace Litium.Application.Examples
{
    [Autostart]
    public class EventBrokerApplicationLifestyleExample
    {
        public EventBrokerApplicationLifestyleExample(EventBroker eventBroker, IApplicationLifetime applicationLifetime)
        {
            var subscription = eventBroker.Subscribe<MyEvent>(ev =>
            {
                // Execute code when the event is raised.
            });

            applicationLifetime.ApplicationStopping.Register(() =>
            {
                // application is about to shutdown, unregister the event listener
                subscription.Dispose();
            });
        }
    }
}
Was this page helpful?
Thank you for your feedback!