Can anyone give me some advice. I am using
Microsoft.Extensions.DependencyInjection version 5.0.1 nuget package
and I would like to get a reference to a ViewModel class that needs a service inject to it, and at the same time pass a parameter to the ViewModel. Here I have an example where the
My class calling a ViewModel that needs to pass a parameter to it also. Can someone tell me how I can do this?
public class ThemeManagementPage : HeadingView
{
private readonly ThemeManagementViewModel _vm;
public ThemeManagementPage(int param1)
{
// This page is called with a parameter and then
// whhat I need to do is to pass the parameter `param1`
// to the ViewModel which I have identified
// as a Transient (see bottom of post)
BindingContext = _vm =
Startup.ServiceProvider.GetRequiredService<ThemeManagementViewModel>();
}
}
public partial class ThemeManagementViewModel : BaseViewModel
{
private readonly IResourceService _resourceService;
public ThemeManagementViewModel(IResourceService resourceService, int param1)
{
_resourceService = resourceService;
var x = param1
}
}
For reference here is my DI setup:
public partial class ResourceService : IResourceService
{
private IDatabaseService _databaseService;
public ResourceService(IDatabaseService databaseService)
{
_databaseService = databaseService;
}
}
public interface IResourceService
{
void SetResourceColors();
}
public static class Startup
{
public static IServiceProvider ServiceProvider { get; set; }
public static IServiceProvider Init()
{
var serviceProvider = new ServiceCollection().ConfigureServices()
.BuildServiceProvider();
ServiceProvider = serviceProvider;
return serviceProvider;
}
}
public static class DependencyInjectionContainer
{
public static IServiceCollection ConfigureServices(this IServiceCollection services)
{
services.AddSingleton<IDatabaseService, DatabaseService>();
services.AddSingleton<IResourceService, ResourceService>();
services.AddTransient<ThemeManagementViewModel>();
return services;
}
}
question from:
https://stackoverflow.com/questions/66057300/how-can-i-send-a-parameter-to-a-viewmodel-that-i-get-a-reference-to-with-this-s 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…