官术网_书友最值得收藏!

  • Xamarin Blueprints
  • Michael Williams
  • 318字
  • 2021-07-08 11:48:23

Autofac

Before we begin implementing the different native sides to this interface, let's first add in our IoC container to handle the abstraction. There are a few IoC containers that are free online; for this example we are going to use Autofac. Let's add the NuGet packages for the PCL, iOS, and Android projects:

Now that we have our IoC container, let's build the iOS implementation. For each platform, we want to create objects called Modules for registering abstracted interfaces. Let's add a new folder called IoC to the PCL project and add a new file called IoC.cs:

public static class IoC 
    { 
        public static IContainer Container { get; private set; } 
 
        private static ContainerBuilder builder; 
 
        public static void CreateContainer()  
        { 
            builder = new ContainerBuilder(); 
        } 
 
        public static void StartContainer() 
        { 
            Container = builder.Build(); 
        } 
 
        public static void RegisterModule(IModule module) 
        { 
            module.Register (builder); 
        } 
 
        public static void RegisterModules(IEnumerable<IModule> modules) 
        { 
            foreach (var module in modules)  
            { 
                module.Register (builder); 
            } 
        } 
 
        public static T Resolve<T>() 
        { 
            return Container.Resolve<T> (); 
        } 
    } 

Looking at this closer, we use this static class for registering modules, registering types, resolving registered types, creating the container, and building the container.

Note

The ContainerBuilder must be built after all types have been registered.

We must register and start this container before we initialize the application. Open up your AppDelegate.cs file and update the FinishedLaunching function:

        public override bool FinishedLaunching (UIApplication app, NSDictionary options) 
        { 
            global::Xamarin.Forms.Forms.Init (); 
 
            InitIoC (); 
 
            LoadApplication (new App ()); 
 
            return base.FinishedLaunching (app, options); 
        } 
 
        private void InitIoC() 
        { 
            IoC.CreateContainer (); 
            IoC.RegisterModule (new IOSModule()); 
            IoC.RegisterModule (new PCLModule()); 
            IoC.StartContainer (); 
        } 

The InitIoC function will first create the container, register the modules, and build the IoC container.

Note

Our container must be created before we can start registering, and our container builder must be built before we can start resolving.

Each module has register functions that will use the created ContainerBuilder to register types.

主站蜘蛛池模板: 五寨县| 天全县| 紫云| 长治县| 偏关县| 集安市| 安塞县| 兴义市| 沙湾县| 靖西县| 蒙阴县| 宁安市| 原平市| 大冶市| 文安县| 盐城市| 虎林市| 藁城市| 中阳县| 永善县| 鄂托克前旗| 邛崃市| 阿巴嘎旗| 弥勒县| 嫩江县| 林甸县| 宝鸡市| 宁海县| 通州区| 永川市| 监利县| 安乡县| 上栗县| 卢氏县| 宝山区| 门源| 阿坝| 广西| 义马市| 万宁市| 正宁县|