• 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

  • 相关阅读:
    leetcode每日一题(2020-06-24):16. 最接近的三数之和
    leetcode每日一题(2020-06-23):67. 二进制求和
    leetcode每日一题(2020-06-19):125. 验证回文串
    leetcode每日一题(2020-06-18):1028. 从先序遍历还原二叉树
    leetcode每日一题(2020-06-17):1014. 最佳观光组合
    leetcode每日一题(2020-06-16):297. 二叉树的序列化与反序列化
    leetcode每日一题(2020-06-14):1300. 转变数组后最接近目标值的数组和
    leetcode每日一题(2020-06-13):70.爬楼梯
    leetcode每日一题(2020-06-12):15. 三数之和
    springboot 项目中_ 利用Filter去解决跨域问题
  • 原文地址:https://www.cnblogs.com/lishidefengchen/p/14522932.html
Copyright © 2020-2023  润新知