【发布时间】: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