private void ConfigureServices(IServiceCollection services) { // https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection?view=dotnet-plat-ext-3.1 services.AddSingleton <MainWindow>(); var serviceInterfacesAndBaseClasses = Assembly.GetEntryAssembly() !.DefinedTypes .Where(candidate => candidate.GetCustomAttribute <ProvideDerivedAttribute>() != null); foreach (var candidate in Assembly.GetEntryAssembly() !.DefinedTypes) { var required = candidate.GetCustomAttribute <SingletonAttribute>() != null; foreach (var derviedFrom in serviceInterfacesAndBaseClasses .Where(fromCandidate => fromCandidate.IsAssignableFrom(candidate) && !candidate.IsAbstract)) { services.AddSingleton(derviedFrom, x => x.GetRequiredService(candidate)); required = true; } if (required) { if (candidate.IsValueType) // For structs. { services.AddSingleton(candidate, _ => Activator.CreateInstance(candidate) !); } else { services.AddSingleton(candidate, candidate); } } } }
public static void MapGrpcServices(this IEndpointRouteBuilder builder) { MethodInfo method = typeof(GrpcEndpointRouteBuilderExtensions).GetMethod("MapGrpcService"); IEnumerable <TypeInfo> typeInfos = Assembly.GetEntryAssembly() !.DefinedTypes.Where(t => t.IsClass && !t.IsAbstract && t.BaseType != null && t.BaseType.CustomAttributes.Any(a => a.AttributeType == typeof(BindServiceMethodAttribute))); foreach (TypeInfo item in typeInfos) { method.MakeGenericMethod(item.AsType()).Invoke(null, new object[] { builder }); } }