Auto-Registering Components

Under the covers, Caliburn uses a dependency injection container for many tasks. Explicit knowledge of this is not necessary in order to use many of Caliburn's features. However, leveraging a container as a central enabling component in a UI architecture can greatly enhance a project. Often times, the process of registering components with a container can become tedious. To this end, Caliburn offers a simple mechanism for the most common registration scenarios. The implementation that Caliburn offers works against Caliburn's container abstraction, thus allowing it to work with anything that implements the IConfigurator and IServiceLocator interfaces.

Declarative Component Registration

Caliburn provides two attributes which a developer can use to declaratively register components with the DI container. These attributes are PerRequest and Singleton. Each of these attributes inherits from RegisterAttribute. You can add your own custom component configuration by inheriting from this attribute as well.

Register a Type as a Singleton (One instance for the Application)
public interface ISettings : INotifyPropertyChanged
{
   ...body of interface definition
}
 
[Singleton(typeof(ISettings))]
public class Settings : IsolatedStorageStateManager, ISettings
{
   ...body of type definition
}

Register a Type as PerRequest (A new instance created on every call to Resolve)
public interface IHomePresenter : IPresenter
{
   ...body of interface definition
}
 
[PerRequest(typeof(IHomePresenter))]
public class HomePresenter : Presenter, IHomePresenter
{
   ...body of type definition
}

Each of the above declarations allows the decorated component to be registered in the DI container using the specified type as its key.

Configuring Caliburn

In addition to decorating your types, you must tell Caliburn which assemblies to search through when auto-registering.

Configuring Caliburn for Auto-registration
private void InitializeCaliburn()
{
    CaliburnFramework
        .ConfigureCore(InitializeContainer())
        .WithAssemblies(Assembly.GetExecutingAssembly())
        .WithPresentationFramework()
        .Start();
}

Notice the use of the WithAssemblies method. This methods accepts a variable length array of Assembly instances. When Caliburn is started, it will reflect against these assemblies looking for decorated types and automatically register them.

Last edited Oct 23, 2009 at 6:55 PM by EisenbergEffect, version 8