简体   繁体   English

Xamarin Android和Dependecy注入

[英]Xamarin Android and Dependecy Injection

I develop an Android application with Xamarin. 我用Xamarin开发了一个Android应用程序。 Suppose I have an Activity and it depends on some interface: 假设我有一个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;
} 

I would like to inject instance of IFoo in MyActivity's constructor but as you know it is impossible to create constructor with parameters. 我想在MyActivity的构造函数中注入IFoo实例,但是如您所知,不可能用参数创建构造函数。 How could I pass initialized instance of IFoo with all its dependencies to MyActivity? 我如何将具有所有依赖项的IFoo初始化实例传递给MyActivity? I use Unity as Dependency Injection framework (but I can change it). 我使用Unity作为依赖注入框架(但可以更改)。

In you app class define: 在您的应用类中定义:

public static UnityContainer container { get; private set; }

var container = new UnityContainer();

register your interface 注册界面

container.RegisterType<IFoo, Foo>();   

and resolve as below 并解决如下

var myFoo = container.Resolve<IFoo>()

Note: Don't forget to add the namespace using Microsoft.Practices.Unity; 注意:不要忘记using Microsoft.Practices.Unity;添加名称空间using Microsoft.Practices.Unity;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM