[英]Dependency injection using Services with Microsoft.Extensions.DependencyInjection library
[英]Xamarin Forms Dependency Injection with Microsoft.Extensions.DependencyInjection
我正在尝试使用标准 Microsoft.Extensions.DependencyInjection NuGet package 设置基本 DI。
目前我正在注册我的依赖项,如下所示:
public App()
{
InitializeComponent();
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
}
private static void ConfigureServices(ServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<IRestClient>(_ => new RestClient("https://localhost:44379/api/"));
serviceCollection.AddScoped<ICommHubClient, CommHubClient>();
}
我使用需要像这样的依赖项的视图模型:
public ChatListViewModel(
ICommHubClient client,
IRestClient restClient
)
在页面的代码隐藏文件(.xaml.cs)中,我需要提供 viewModel,但我也需要在那里提供依赖项。
public ChatListPage()
{
InitializeComponent();
BindingContext = _viewModel = new ChatListViewModel(); //CURRENTLY THROWS ERROR BECAUSE NO DEPENDENCIES ARE PASSED!
}
有谁知道我如何在 Xamarin Forms 中使用 Microsoft.Extensions.DependencyInjection 应用依赖注入(注册和解析)?
您还应该在 DI Container 中注册您的 ViewModel,而不仅仅是您的服务:
在App.xaml.cs
您的代码更改为:
public ServiceProvider ServiceProvider { get; }
public App()
{
InitializeComponent();
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
ServiceProvider = serviceCollection.BuildServiceProvider();
MainPage = new ChatListPage();
}
private void ConfigureServices(ServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<IRestClient>(_ => new RestClient("https://localhost:44379/api/"));
serviceCollection.AddScoped<ICommHubClient, CommHubClient>();
serviceCollection.AddTransient<ChatListViewModel>();
}
然后您可以从ServiceProvider
解析您的 ViewModel
public ChatListPage()
{
InitializeComponent();
BindingContext = _viewModel = ((App)Application.Current).ServiceProvider.GetService(typeof(ChatListViewModel)) as ChatListViewModel;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.