I found some examples where generic method is invoked via reflection such as method<T>()
. In my case, the generic type is nested in a class method<Class<T>>()
.
In the example, I redirect the view model of a WPF app. I have as many view models as View
enums. As I keep adding new views / view models, I would avoid to duplicate the lines of code. _serviceProvider
is provided by Microsoft Dependency Injection.
switch (view)
{
case View.Settings:
ViewModel = _serviceProvider.GetRequiredService<CreateViewModel<SettingsViewModel>>().Invoke();
break;
// ...
}
What I put together so far. Can someone hepl me correct it?
using System;
using System.Reflection;
namespace NestedGenericReflection
{
class Program
{
private static ServiceProviderModel _serviceProvider = new ServiceProviderModel();
static void Main(string[] args)
{
var view = View.Settings;
IViewModel viewModel = null;
var assembly = typeof(IViewModel).Assembly;
var typeName = $"NestedGenericReflection.{view}ViewModel, {assembly.FullName}";
var type = Type.GetType(typeName);
var generic = typeof(CreateViewModel<>).MakeGenericType(type); // I believe this is not correct..
var property = typeof(Program).GetProperty(nameof(_serviceProvider), BindingFlags.NonPublic | BindingFlags.Static); // Static for this example.
var method = property.PropertyType
.GetMethod("GetRequiredService")
.MakeGenericMethod(generic);
var instance = Activator.CreateInstance(type); // Not sure.
viewModel = method.Invoke(instance, null) as IViewModel;
}
}
public enum View
{
Settings
}
public interface IViewModel
{
}
public interface IService
{
IViewModel Invoke();
}
public class ServiceProviderModel
{
public IService GetRequiredService<T>()
{
return null;
}
}
public class SettingsViewModel : IViewModel
{
}
public class CreateViewModel<ViewModel> where ViewModel : class
{
}
}