Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Last active October 4, 2021 17:14
Show Gist options
  • Save DamianSuess/f151bc1b31af3c80218350ecf35d3be6 to your computer and use it in GitHub Desktop.
Save DamianSuess/f151bc1b31af3c80218350ecf35d3be6 to your computer and use it in GitHub Desktop.
C# Auto-wire Classes for DI
// This is an example of configuring Microsoft DI to auto-wire classes with the suffix, 'Actor'.
// Usage:
// In your ASP.NET Core's Startup.cs method, ConfigureServices, add the following line
// ``services.AddActors();``
// The system will then scan for all classes which end with the name, 'Actor' and register
// them as singletons.
public static class DependencyExtension
{
/// <summary>Auto-wire state machine actors, directors, or coordinators.</summary>
/// <param name="service">MS IOC service.</param>
/// <param name="suffix">Suffix of the state machine type to register.</param>
public static void AddActors(this IServiceCollection service, string suffix = "Actor")
{
var assembly = Assembly.GetExecutingAssembly();
// search for supplied suffix, but not classes starting with 'I' for interface.
var services = assembly.GetTypes().Where(type =>
type.GetTypeInfo().IsClass &&
type.Name.EndsWith(suffix) &&
!type.Name.StartsWith("I") &&
!type.GetTypeInfo().IsAbstract);
foreach (var serviceType in services)
{
var allInterfaces = serviceType.GetInterfaces();
var mainInterfaces = allInterfaces.Except(allInterfaces.SelectMany(t => t.GetInterfaces()));
foreach (var iServiceType in mainInterfaces)
{
service.AddSingleton(iServiceType, serviceType);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment