如何解决Xamarin 使用 Microsoft.Extensions.DependencyInjection 形成依赖注入
我正在尝试使用标准 Microsoft.Extensions.DependencyInjection NuGet 包设置基本 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>();
}
我使用的 viewmodel 需要这样的依赖项:
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
public ChatListPage()
{
InitializeComponent();
BindingContext = _viewModel = ((App)Application.Current).ServiceProvider.GetService(typeof(ChatListViewModel)) as ChatListViewModel;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。