【问题标题】:Xamarin Android and Dependecy InjectionXamarin Android 和依赖注入
【发布时间】:2017-10-09 22:44:17
【问题描述】:

我使用 Xamarin 开发了一个 Android 应用程序。假设我有一个 Activity,它依赖于某个接口:

interface IFoo
{
    // methods
}

public class Foo : IFoo
{
    private readonly IBar _bar;

    public Foo(IBar bar)
    {
        _bar = bar;
    }

    // methods implementation
}
// dependency injection somewhere in Application class
var container = new UnityContainer();
container.RegisterType<IFoo, Foo>();   

public class MyActivity : Activity
{
    // it's incorrect constructor and this code will not be compiled
    public MyActivity(IFoo foo)
    {
        _foo = foo;
    }

    private readonly IFoo _foo;
} 

我想在 MyActivity 的构造函数中注入 IFoo 的实例,但如您所知,不可能创建带参数的构造函数。如何将 IFoo 的初始化实例及其所有依赖项传递给 MyActivity?我使用 Unity 作为依赖注入框架(但我可以更改它)。

【问题讨论】:

  • 为什么要在MyActivity的构造函数中注入IFoo的实例?如果你想初始化UnityContainer,你可以在AndroidApplication类中进行。
  • @YorkShen-MSFT 我如何在 Activity 类中使​​用它?
  • @Pupkin 你解决了这个问题吗?如果有,你是怎么做到的?

标签: c# android xamarin dependency-injection xamarin.android


【解决方案1】:

在你的应用类中定义:

public static UnityContainer container { get; private set; }

var container = new UnityContainer();

注册你的接口

container.RegisterType<IFoo, Foo>();   

并解决如下

var myFoo = container.Resolve<IFoo>()

注意:不要忘记添加命名空间using Microsoft.Practices.Unity;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多