Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Created January 12, 2022 22:49
Show Gist options
  • Select an option

  • Save DamianSuess/af6aa7e02dc0bc2ec23db0d42d6d6d05 to your computer and use it in GitHub Desktop.

Select an option

Save DamianSuess/af6aa7e02dc0bc2ec23db0d42d6d6d05 to your computer and use it in GitHub Desktop.
Auto detect classes with the suffix 'Actor' and register as Singleton with DI
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
namespace Xeno.StateMachine.Extensions
{
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