【发布时间】:2021-06-16 03:48:59
【问题描述】:
我正在尝试使用标准 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 应用依赖注入(注册和解析)?
【问题讨论】:
标签: c# xamarin xamarin.forms dependency-injection dependencies