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

posted @ 2021-03-12 11:45  lishidefengchen  阅读(397)  评论(0编辑  收藏  举报