c# - Xamarin 使用 Microsoft.Extensions.DependencyInjection 形成依赖注入(inject)

标签 c# xamarin xamarin.forms dependency-injection dependencies

我正在尝试使用标准 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 应用依赖注入(inject)(注册和解析)?

最佳答案

您还应该在 DI 容器中注册您的 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;
}

关于c# - Xamarin 使用 Microsoft.Extensions.DependencyInjection 形成依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66696261/

相关文章:

xamarin - 如何创建具有属性的自定义控件

c# - HttpClient 不适用于 android

xamarin.forms - Xamarin 表格 : Image Slider: CarouselPage - Out of Memory

c# - 在 Unity3d 中使用 IEnumerator 与 IEnumerable 的嵌套协程

c# - 使用 ASP.NET MVC 中的自定义登录页面进行 Intranet Windows 身份验证

c# - System.Threading.Timer导致其他计时器落后

c# - 在 C# 中从后端发送 UWP 原始通知

xamarin 表单与 mvvmcross 一起使用

C# 私有(private)、静态和只读

c# - 在 Xamarin Forms 中滚动时如何折叠(隐藏或向上滑动)导航栏(标题栏)?