使用 Autofac 无法传递 Android 上下文

Failing to pass Android Context using Autofac

我决定试试 Xarmarin,我想传递 android 上下文。

我以前用 Android 和 Roboguice 做过类似的想法。他们有一个供应商工厂,可以让您传递该项目以通过属性注入。

我想用 IoC 尝试这种方法(最好是 Autofac)。我遵循了这个例子:http://arteksoftware.com/ioc-containers-with-xamarin/

我想补充一点,我发现很难通过构造函数注入实例的服务。

你们都做到了吗?

I've decided to give Xarmarin a try, and I'd like to pass the android context.

直接传递android上下文?不,没有办法做到这一点。接口在 PCL 中定义,但在 PCL 中没有合适的容器(类型)来接受上下文实例。

但是您可以定义自己的接口和class以利用上下文实例:

基于您发布的博客演示的示例(利用上下文读取 Assets 文件夹中的 txt 文件):

  1. Assets 文件夹中添加一个 txt 文件(abc.txt) 并将其 BuildAction 设置为 AndroidAssets
  2. 在PCL中定义一个新接口:

    public interface IContextUtility
    {
        string GetAssetTxt(string str);
    }
    
  3. MainViewModel.cs中添加一个IContextUtility的变量:

    public class MainViewModel
    {
        private readonly IPlatform _platform;
        private readonly ISettings _settings;
        private readonly IContextUtility _contextUtility;
    
        public MainViewModel (IPlatform platform, ISettings settings,IContextUtility contextUtility)
        {
            _settings = settings;
            _platform = platform;
            _contextUtility = contextUtility;
        }
    
        public string Abc
        {
            get {
                return _contextUtility.GetAssetTxt("abc.txt");
            }
        }
      ...
    }
    
  4. 在Android项目中添加IContextUtility实现:

    public class MyContextUtility : IContextUtility
    {
        public string GetAssetTxt(string str)
        {
            string strToReturn = null;
            using (var stream = Application.Context.Assets.Open(str))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    strToReturn=reader.ReadToEnd();
                }
            }
            return strToReturn;
        }
    }
    
  5. App.cs中注册一个新实例:

    [Application(Icon="@drawable/icon", Label="@string/app_name")]
    public class App : Application
    {
        public static IContainer Container { get; set; }
    
        public App(IntPtr h, JniHandleOwnership jho) : base(h, jho)
        {
        }
    
        public override void OnCreate()
        {
            var builder = new ContainerBuilder();
            builder.RegisterInstance(new MyContextUtility()).As<IContextUtility>();
            ...
        }
    }
    
  6. 现在,您可以在 MainActivity 中使用它了:

    var text = viewModel.Abc;