Created
October 2, 2012 14:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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