首页 > 解决方案 > 动态地将 T 传递给方法

问题描述

我已经按照这篇文章为 .Net Core WebAPI 创建了一个可写选项类。我使用这个类来更新我的appsettings.json文件。

我想动态创建这些可写选项类。例如,我有多个选项类,例如OptionsA,OptionsB等等。它们可以在该文件中进行配置,appsettings.json并且仅应在它们存在于该文件中时才被注入。

到目前为止一切顺利,现在我的问题是ConfigureWritable有一个类型参数T。我的问题是,当我的代码OptionsAappsettings.json文件中找到时,如何为ConfigureWritable方法提供类型?

这是我到目前为止所拥有的:

private void AddOptionalServices(IServiceCollection services, ServiceSettings serviceSettings)
{
    foreach (var serviceSetting in serviceSettings.Services)
    {
        var serviceType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.Name == serviceSetting.Name).FirstOrDefault();
        var settingsType = (Type)serviceType.GetProperty("ServiceType").GetValue(serviceType, null);


        services.AddSingleton(typeof(IHostedService), serviceType);
        services.ConfigureWritable<settingsType>(Configuration.GetSection("")); //Problem lies here
    }
}

settingsType是从 serviceType 返回的属性。

编辑:基于 Lasse 的评论的第二次尝试:

private void AddOptionalServices(IServiceCollection services, ServiceSettings serviceSettings)
{
    foreach (var serviceSetting in serviceSettings.Services)
    {
        var serviceType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.Name == serviceSetting.Name).FirstOrDefault();
        var settingsType = (Type)serviceType.GetProperty("ServiceType").GetValue(serviceType, null);

        services.AddSingleton(typeof(IHostedService), serviceType);
        var method = typeof(IServiceCollection).GetMethod("ConfigureWritable"); //returns null
        var methods = typeof(IServiceCollection).GetMethods(); //returns empty enumeration
        var generic = method.MakeGenericMethod(settingsType);
        generic.Invoke(this, null);
    }
}

如您所见,我在使用GetMethod.

标签: c#dynamic.net-coretype-parameter

解决方案


推荐阅读