我有一个包含多个托管服务的网络服务。
我希望能够通过“appSettings.json”打开和关闭它们。
在“StartUp.cs”中,我填充了一个实例
public class HostedServiceSettings
{
public StateOfUse BuildMontageTasks { get; init; }
public StateOfUse BuildTasksFromFileCreations { get; init; }
public StateOfUse BusinessEventPuller { get; init; }
public StateOfUse FieldServiceAppointmentChanges { get; init; }
public StateOfUse MvtBriefingCleanupLoop { get; init; }
public StateOfUse SfCacheFileListener { get; init; }
public StateOfUse TaskWorker { get; init; }
}
StateOfUse
这个枚举是:
public enum StateOfUse
{
Inactive,
Active
}
每个属性对应一个托管服务。
回到StartUp
课堂上,我添加了以下方法:
private void AddHostedServices(IServiceCollection services)
{
HostedServiceSettings settings = Configure<HostedServiceSettings>(services, "HostedServices");
foreach (PropertyInfo property in typeof(HostedServiceSettings).GetProperties())
{
StateOfUse stateOfUse = (StateOfUse)property.GetValue(settings);
if (stateOfUse.IsActive())
{
string hostedServiceName = $"PraxedoIntegration.{property.Name}HostedService";
Type hostedServiceType = Type.GetType(hostedServiceName);
Type type = typeof(IServiceCollection);
MethodInfo methodInfo = type.GetMethod("IServiceCollection.AddHostedService");
MethodInfo genericMethod = methodInfo.MakeGenericMethod(hostedServiceType);
genericMethod.Invoke(services, null);
}
}
}
这会失败,因为MethodInfo methodInfo
解析为 null,因此将在下一行引发异常。该方法IServiceCollection.AddHostedService<THostedService>()
是一个静态方法,包含Microsoft.Extensions.DependencyInjection
在public static class ServiceCollectionHostedServiceExtensions
. (我不在nameof
代码中使用,因为扩展方法不支持。:-()
是否可以通过泛型访问此方法?如果是这样,怎么做?