zoukankan      html  css  js  c++  java
  • xamarin.forms 使用依赖注入


    #添加nuget包(第一个类库项目中)

    AutoFac

    AutoFac.Extras.Common.ServiceLocator

    # 再添加一个新的类库(.net standard library 2.0/2.1) 

    ServiceManager

    该层负责数据访问,会被主类库项目使用

    #在这个数据访问层项目中,添加EmployeeService.cs类文件:

    using System;
    using System.Collections.Generic;
    
    namespace ServiceManager
    {
        public class EmployeeService : IEmployeeService
        {
            public EmployeeService()
            {
            }
    
            /// <summary>
            /// get employee name mock data
            /// </summary>
            /// <returns></returns>
            public List<string> GetEmployeeNameList()
            {
                var list = new List<string>
                {
                    "Shravan Madavu", 
                    "Joshi naveen",
                    "Kotte Jayan",
                    "Ravi naganna",
                    "Kiran kumar",
                    "Elicia Esposito", 
                    "Vivien Perras"
                };
    
                return list;
            }
        }
    }
    View Code

    #添加接口类文件:

    using System.Collections.Generic;
    
    namespace ServiceManager
    {
        public interface IEmployeeService
        {
            List<string> GetEmployeeNameList();
        }
    }
    View Code

    #在主类库项目中,添加AutoFac容器注入维护类文件:

    public sealed class AutoFacContainer
        { 
            public static void Initialize()
            {
                ContainerBuilder containerBuilder = new ContainerBuilder();
                containerBuilder.RegisterType<MainPageViewModel>().AsSelf();
                containerBuilder.RegisterType<EmployeeService>().As<IEmployeeService>();
    
                IContainer container = containerBuilder.Build();
    
                AutofacServiceLocator autofacServiceLocator = new AutofacServiceLocator(container);
                ServiceLocator.SetLocatorProvider(() => autofacServiceLocator); 
            }
        }
    View Code

    #创建UI xaml文件 MainPage.xaml:

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:d="http://xamarin.com/schemas/2014/forms/design"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 mc:Ignorable="d"
                 x:Class="SampleAutoFacDI.MainPage"
                 BindingContext="{Binding MainPageViewModel,Source= {StaticResource Locator}}"> 
     <StackLayout>
       <ListView ItemsSource="{Binding EmployeeCollection}" >
          <ListView.ItemTemplate>
             <DataTemplate>
                <ViewCell>
                   <StackLayout Padding="10">
                      <Label Text="{Binding}" FontSize="Medium"/>
                    </StackLayout>
                 </ViewCell>
              </DataTemplate>
           </ListView.ItemTemplate>
        </ListView>
      </StackLayout> 
    </ContentPage>
    View Code

    #在ViewModels文件夹下,创建 ViewModelLocator.cs:

    using CommonServiceLocator;
    namespace SampleAutoFacDI.ViewModels
    {
        public class ViewModelLocator
        {
            static ViewModelLocator()
            {
                AutoFacContainer.Initialize();
            }
    
            public MainPageViewModel MainPageViewModel
            {
                get
                {
                    return ServiceLocator.Current.GetInstance<MainPageViewModel>();
                }
            }
        }
    }
    View Code

    #修改 App.xaml 使用 locater 关键字关联我们的资源目录:

    上面 MainPage.xaml 文件中,定义的静态资源关键字——BindingContext="{Binding MainPageViewModel,Source= {StaticResource Locator}}">

    <?xml version="1.0" encoding="utf-8" ?>
    <Application xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:d="http://xamarin.com/schemas/2014/forms/design"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 mc:Ignorable="d"
                 xmlns:vm="clr-namespace:SampleAutoFacDI.ViewModels"
                 x:Class="SampleAutoFacDI.App">
        <Application.Resources>
    <ResourceDictionary>
        <vm:ViewModelLocator x:Key="Locator"/>
        </ResourceDictionary>
        </Application.Resources>
    </Application>
    View Code

    #最后,创建 MainPageViewModel.cs:

    using System.Collections.ObjectModel;
    using ServiceManager;
    
    namespace SampleAutoFacDI.ViewModels
    {
        public class MainPageViewModel
        { 
            private readonly IEmployeeService _employeeService;
            private ObservableCollection<string> _employeeCollection;
            public ObservableCollection<string> EmployeeCollection
            {
                get
                {
                    return _employeeCollection;
                }
            }
    
            public MainPageViewModel(IEmployeeService employeeService)//Injected service data here
            {
                _employeeService = employeeService;
                InitializeData();
            }
    
            private void InitializeData()
            { 
                var empList = _employeeService.GetEmployeeNameList();
                _employeeCollection = new ObservableCollection<string>();
                empList.ForEach(emp => _employeeCollection.Add(emp));
            }
        }
    }
    View Code

    完毕!

    参考:https://www.appliedcodelog.com/2020/06/dependency-injection-in-xamarin-form.html

  • 相关阅读:
    Qt class加载头文件
    Qt 中KeyPressEvent获取不到Key_Space等事件
    如何选择开源许可证?
    C语言实现库函数汇总
    简单背包问题-递归非递归实现
    中点优先顺序遍历数组-递归非递归实现
    稀疏矩阵十字链表表示
    稀疏矩阵线性表示
    KMP模式匹配
    双向链表
  • 原文地址:https://www.cnblogs.com/lishidefengchen/p/14522932.html
Copyright © 2011-2022 走看看