I develop an Android application with Xamarin. Suppose I have an Activity and it depends on some interface:
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. How could I pass initialized instance of IFoo with all its dependencies to MyActivity? I use Unity as Dependency Injection framework (but I can change it).
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.