So I'm currently looking at some code and I'm trying to figure out how this line manages to resolve the "factory" which apparently is nothing but a delegate that takes a "Type" and returns an object. It's hard for me to form this question because I don't fully understand what's going on. Could someone break it down?
It all starts in the App.cs
public App()
{
IServiceCollection _services = new ServiceCollection();
_services.AddSingleton<MainViewModel>();
_services.AddSingleton<HomeViewModel>();
/* This is the part I don't understand */
_services.AddSingleton<INavigationService, NavService>(sp =>
{
return new NavService(type => sp.GetRequiredService(type));
});
...
_serviceProvider = _services.BuildServiceProvider();
}
This essentially builds the singleton instance that we're registering
_services.AddSingleton<INavigationService, NavService>(sp =>
{
return new NavService(type => sp.GetRequiredService(type));
});
And we're passing in whatever sp.GetRequiredService(type)
returns as a parameter to the NavService
constructor.
Which seems to be a Func<Type, object>
? Why?
And what is type
that we're using when we're using the lambda statement type => sp.GetRequiredService(type)
How do we resolve a Func<Type, object>
from type
?
Inside the NavService
we're utilizing that delegate by invoking it with a type, which I believe resolves the singleton instance of whatever type we're using when calling NavigateTo<T>
public class NavService : ObservableObject, INavigationService
{
private readonly Func<Type, object> factory;
private object _currentView;
public NavService(Func<Type, object> factory)
{
this.factory = factory;
}
public object CurrentView
{
get => _currentView;
private set
{
_currentView = value;
OnPropertyChanged();
}
}
public void NavigateTo<T>() where T : ViewModel
{
object viewModel = factory.Invoke(typeof(T)) ?? throw new InvalidOperationException("Could not locate VM.");
CurrentView = viewModel;
}
}
So my best guess is that, what we pass in through the constructor is the actual "factory" behind the Microsoft.Extensions.DependencyInjection
package that I'm using which is responsible for newing up instances of dependencies that we're registering.
But that still doesn't answer my question of how we resolve a Func<Type, object>
from type
which is just of type Type
?