services.AddSingleton<NavigationBarViewModel>();
services.AddSingleton<FileHandlingViewModel>();
services.AddSingleton<SchedulingProblemViewModel>();
....
services.AddSingleton<Func<FileHandlingViewModel>>((s) => () => s.GetRequiredService<FileHandlingViewModel>());
services.AddSingleton<Func<SchedulingProblemViewModel>>((s) => () => s.GetRequiredService<SchedulingProblemViewModel>());
services.AddSingleton<Func<TimeIntervalsViewModel>>((s) => () => s.GetRequiredService<TimeIntervalsViewModel>());
...
I register a bunch of Func
as indicated above into MS DI container. I can list the relevant types with reflection. I can auto-register the types, but I also want to auto-register the Func
s with foreach
. Any idea for the later?
It seems auto-registration of factory method can not be done in MS DI. The problem is that we can create the factory method with
MakeGenericMethod
but this method still needs an explicit cast what we can not use in an auto-registration loop.Workaround: Use factory class instead of factory method.
Storing
IServiceProvider
in the Factory class seems to be the service locator ani-pattern but MS DI does the same when we register a Func manually. Now we can usePageViewModelFactory<FileHandlingViewModel>.Create
instead ofFunc<FileHandlingViewModel>
.