Skip to content

Instantly share code, notes, and snippets.

@galaktor
Created October 2, 2012 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galaktor/3819481 to your computer and use it in GitHub Desktop.
Save galaktor/3819481 to your computer and use it in GitHub Desktop.
how to register a class and force the container to activate an instance of T once after configuration completed
public class StartableBootstrap<T>: IStartable
{
private readonly IComponentContext _context;
public StartableBootstrap(IComponentContext context)
{
_context = context;
}
public void Start()
{
_context.Resolve<T>();
}
}
public static class AutofacExtensions
{
/// <summary>
/// Forces resolve of a single instance of T. Useful for services that are not dependend on by any other component
/// but need to be instantiated in the system.
/// </summary>
/// <typeparam name="T">The type of the service.</typeparam>
/// <param name="b">The container builder used to register the service.</param>
public static IRegistrationBuilder<T, ConcreteReflectionActivatorData, SingleRegistrationStyle> RegisterAndActivate<T>(this ContainerBuilder b)
{
b.RegisterType<StartableBootstrap<T>>()
.As<IStartable>()
.SingleInstance();
return b.RegisterType<T>();
}
}
public class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAndActivate<MyClass>()
.SingleInstance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment