C# Xamarin使用Microsoft.Extensions.DependencyInjection形成依赖项注入
我正在尝试使用标准的Microsoft.Extensions.DependencyInjection NuGet包设置基本DI 目前我正在注册我的依赖项,如下所示:C# Xamarin使用Microsoft.Extensions.DependencyInjection形成依赖项注入,c#,xamarin,xamarin.forms,dependency-injection,dependencies,C#,Xamarin,Xamarin.forms,Dependency Injection,Dependencies,我正在尝试使用标准的Microsoft.Extensions.DependencyInjection NuGet包设置基本DI 目前我正在注册我的依赖项,如下所示: public App() { InitializeComponent(); var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); } private static void Configu
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表单中使用Microsoft.Extensions.DependencyInjection应用依赖项注入(注册和解析)?您还应该在DI容器中注册ViewModels,而不仅仅是您的服务: 在
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>();
}
您还应该在DI容器中注册ViewModels,而不仅仅是您的服务: 在
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>();
}
同时添加页面并将视图模型作为构造函数arg放置,以便同时注入视图模型。同时添加页面并将视图模型作为构造函数arg放置,以便同时注入视图模型。