When writing cross platform apps with Xamarin, our goal is share as close to 100% of our code across all the platforms. While this is an admirable goal to aim for, it is not realistic. Very often, we find ourselves needing to access a platform specific feature from our shared code. We have multiple options in this case. We could use a Shared Project with compiler directives, class mirroring, or partial classes and access the platform code alongside our shared code. Alternatively we could use an abstraction for the functionality in our shared code, and pass an implementation of the abstraction into our shared code. In this way, our shared code only needs to know about the abstraction, typically an interface. This strategy, known as Inversion of Control or IoC, works especially well when using Portable Class Libraries (PCL) for our shared code.

Even when using IoC, manually managing all of our dependencies, including instantiating the dependency tree for an object, can be tedious at best. This is where we turn to a host of existing IoC containers. The .net ecosystem has long had a wealth of choices in IoC containers. Some of the more popular ones include StructureMapCastle WindsorNinjectUnity, and Autofac. These are by no means the only choices, up to and including rolling our own.

Not all of these containers are able to run in limitations imposed by mobile devices though. Phones and tablets have constrained cpu and memory, and iOS devices forbid JIT compiling and certain uses of reflection. Additionally, the library authors have to specifically compile for Xamarin.iOS and Xamarin.Android, either individually or as part of a PCL.

I decided to put together some sample code showing how the Xamarin-compatible IoC containers work. As of this writing (July, 2014) I have limited the comparison only to IoC containers that 1) I could get to work successfully and 2) had an available Nuget package for easy installation. I did not want to go through the process of pulling individual repositories and building the source from scratch, although that is a valid option. This excluded some options that I do want to mention as alternatives.

  • Xamarin.Forms Dependency Service. This is really more of a Service Locator than it is an IoC container. Also, it is only available as part of Xamarin.Forms.
  • OpenNetCF. There is no nuget package for this library. Also, it requires custom attributes be added to the shared code, diminishing the usefulness.
  • XPlatUtils. There is no nuget package for this library.

The libraries that I focused on were AutofacMvvmCrossNinjectTinyIoc, and Unity.

All of the code is available from my Github Repo

Sample Project

In the sample project, we have a single IoCDemo.Core project. This project contains the interface abstractions for our platform specific projects (ISettings and IPlatform) and a concrete ViewModel (MainViewModel) which takes the two interfaces as constructor dependencies. For each library, I created an iOS and an Android project to demonstrate wiring up the dependencies to platform specific implementations and creating the view model. Each container will be wired up in an App.cs file in each platform.

Some of the IoC containers have the ability to scan your assemblies and automatically wire up your dependecies. I chose not to use this ability. In a mobile app, every bit of cpu power is precious. I would rather spend the extra few seconds to write the code to wire up the dependency once at development time than have the app scan the assemblies every single time it is started.

Autofac

Install-Package Autofac

Wiring up the container

using Autofac;
using IoCDemo.Core; namespace AutoFacDemo.iOS
{
public class App
{
public static IContainer Container { get; set; } public static void Initialize()
{
var builder = new ContainerBuilder(); builder.RegisterInstance(new ApplePlatform()).As<IPlatform>();
builder.RegisterInstance(new AppleSettings()).As<ISettings>();
builder.RegisterType<MainViewModel> (); App.Container = builder.Build ();
}
}
}

Resolving the view model

MainViewModel viewModel = null;

using (var scope = App.Container.BeginLifetimeScope ()) {
viewModel = App.Container.Resolve<MainViewModel> ();
}

MvvmCross

Install-Package MvvmCross.HotTuna.CrossCore

Wiring up the container

using Cirrious.CrossCore;
using IoCDemo.Core;
using Cirrious.CrossCore.IoC; namespace MvvmCrossDemo.iOS
{
public static class App
{
public static void Initialize ()
{
MvxSimpleIoCContainer.Initialize ();
Mvx.RegisterType<IPlatform, ApplePlatform> ();
Mvx.RegisterType<ISettings, AppleSettings> ();
}
}
}

Resolving the view model

var viewModel = Mvx.IocConstruct<MainViewModel> ();

Ninject

Install-Package Portable.Ninject

Wiring up the container

using Ninject;

namespace NinjectDemo.iOS
{
public static class App
{
public static StandardKernel Container { get; set; } public static void Initialize()
{
var kernel = new Ninject.StandardKernel(new NinjectDemoModule()); App.Container = kernel;
}
}
}

Resolving the view model

var viewModel = App.Container.Get<MainViewModel> ();

TinyIoc

Install-Package TinyIoc

Wiring up the container

using TinyIoC;
using IoCDemo.Core; namespace TinyIoCDemo.iOS
{
public static class App
{
public static void Initialize ()
{
var container = TinyIoCContainer.Current; container.Register<IPlatform, ApplePlatform> ();
container.Register<ISettings, AppleSettings> ();
}
}
}

Resolving the view model

var viewModel = TinyIoC.TinyIoCContainer.Current.Resolve<MainViewModel> ();

Unity

Install-Package Unity

Wiring up the container

using Microsoft.Practices.Unity;
using IoCDemo.Core; namespace UnityDemo.iOS
{
public class App
{
public static UnityContainer Container { get; set; } public static void Initialize()
{
App.Container = new UnityContainer();
App.Container.RegisterType<IPlatform, ApplePlatform> ();
App.Container.RegisterType<ISettings, AppleSettings> ();
}
}
}

Resolving the view model

var viewModel = App.Container.Resolve (typeof(MainViewModel), "mainViewModel") as MainViewModel;

Again, checkout the sample app on my Github repo to compare our IoC container choices for Xamarin.

From:http://arteksoftware.com/ioc-containers-with-xamarin/

IoC Containers with Xamarin的更多相关文章

  1. MVVMLight - IOC Containers and MVVM

    在面向对象编程的早期,开发者要面对在应用程序或者类库中创建或检索类的实例的问题.针对这个问题有很多的解决方案.在过去几年中,依赖注入(DI)和控制反转(IoC)在开发者中很流行,并且取代了老的方案,比 ...

  2. [VueJS + Typescript] Decouple Dependencies Using IoC Containers in Vue with TypeScript and InversifyJS

    Using Object Oriented Programming, OOP, style allows us to apply Inversion of Control, IoC, and more ...

  3. [LINK]List of .NET Dependency Injection Containers (IOC)

    http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx I'm trying to expand my ...

  4. 译:Spring框架参考文档之IoC容器(未完成)

    6. IoC容器 6.1 Spring IoC容器和bean介绍 这一章节介绍了Spring框架的控制反转(IoC)实现的原理.IoC也被称作依赖注入(DI).It is a process wher ...

  5. How to Make Portable Class Libraries Work for You

    A Portable Class Library is a .NET library that can be used (in binary form, without recompiling) on ...

  6. MVC Controller Dependency Injection for Beginners【翻译】

    在codeproject看到一篇文章,群里的一个朋友要帮忙我翻译一下顺便贴出来,这篇文章适合新手,也算是对MEF的一个简单用法的介绍. Introduction In a simple stateme ...

  7. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->关于spring framework中的beans

    Spring framework中的beans 1.概述 bean其实就是各个类实例化后的对象,即objects spring framework的IOC容器所管理的基本单元就是bean spring ...

  8. Asp.Net Web API 2第十一课——在Web API中使用Dependency Resolver

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文主要来介绍在Asp.N ...

  9. How To Easily Call WCF Services Properly z

    Please note: this article has been superceded by the documentation for the ChannelAdam WCF Library. ...

随机推荐

  1. 洛谷P2312解方程

    传送门 思路分析 怎么求解呢? 其实我们可以把左边的式子当成一个算式来计算,从1到 $ m $ 枚举,只要结果是0,那么当前枚举到的值就是这个等式的解了.可以通过编写一个 $ bool $ 函数来判断 ...

  2. 关于主键的设计、primary key

    主键:用于唯一标识一个表中一行数据. 外键:用于建立两个表之间的关系,A表中有一列是B表中的主键,那么A表中这列的数据就受到B表主键的约束. 那么关于主键应该如何设计呢,这里我说下优缺点: 1.用自动 ...

  3. Ubuntu 搭建ELK

    一.简介 官网地址:https://www.elastic.co/cn/ 官网权威指南:https://www.elastic.co/guide/cn/elasticsearch/guide/curr ...

  4. **PHP foreach 如何判断为数组最后一个最高效?

    http://www.zhihu.com/question/20158667 其他方法: $list = array('a', 'b', 'c'); foreach($list as $k=>$ ...

  5. nginx+keepalived高可用服务器宕机解决方案

    http://blog.51cto.com/gdutcxh/2109841 https://blog.csdn.net/winsonyuan/article/details/52784988

  6. CCF CSP 201412-3 集合竞价

    CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址 CCF CSP 201412-3 集合竞价 问题描述 某股票交易所请你编写一个程序,根据开盘前客户提交的订单来确 ...

  7. RabbitMQ系列之高可用集群

    为了实现高可用,我采用LVS+双节点RabbitMq , 架构图如下: 在RabbitMQ之前放了LVS, LVS 采用 rr 轮询算法 , 目的是将请求平均分配到两个真实节点,并配置5672端口监控 ...

  8. 多线程-TaskExecutor-使用Demo

    BasicExecute.java package com.jef.executeTest; public abstract class BasicExecute extends Thread { @ ...

  9. 【LOJ】#2027. 「SHOI2016」黑暗前的幻想乡

    题解 我一开始写的最小表示法写的插头dp,愉快地TLE成60分 然后我觉得我就去看正解了! 发现是容斥 + 矩阵树定理 矩阵树定理对于有重边的图只要邻接矩阵的边数设置a[u][v]表示u,v之间有几条 ...

  10. Kibana安装及简单使用

    Kibana安装 参照官方文档即可,这里只做相关操作记录: wget https://artifacts.elastic.co/downloads/kibana/kibana-5.5.0-linux- ...