Search code examples
c#dependency-injectionxamarin.formsunity-container

Chain of dependencies using Unity Dependency Injection and Xamarin.Forms


I'm new to Dependency Injection, and I'm developing an App using Xamarin.Forms, Prism and Unity. So as far as I know, when using DI you want to supply/inject services to classes so they don't have to get them. Resulting in classes that have no knowledge of service implementations.

That means using Constructor Injection instead of using the Container to resolve the services. Also seen here http://structuremap.github.io/quickstart.

My setup:

[assembly: Xamarin.Forms.Dependency(typeof(Foo))]
public class Foo : IFoo
{
    public IBar Bar { get; private set; }

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

[assembly: Xamarin.Forms.Dependency(typeof(Bar))]    
public class Bar : IBar
{ }

Now if I would try to resolve IFoo an exception is thrown: System.MissingMethodException: Default constructor not found for type Foo What is going on here?

I have also tried adding an empty constructor to Foo, but this results in Bar being null and forces me to resolve it from the IUnityContainer.


Solution

  • Roughly put as far as I can tell the Xamarin forms dependency services(which it looks like you are using) doesn't provide constructor injection. So if you want to do constructor based injection you will need to use a different container service.

    IF you want to use the built in Forms service the following changes to your code should work..

    [assembly: Xamarin.Forms.Dependency(typeof(Foo))]
    public class Foo : IFoo
    {
    public IBar Bar { get; set; }
    
     public Foo(IBar bar)
     {
        Bar = bar;
     }
    }
    
    [assembly: Xamarin.Forms.Dependency(typeof(Bar))]    
    public class Bar : IBar
    { }
    

    Then to get your object set:

      var myFoo =  Xamarin.Forms.Dependency.Get<IFoo>();
      myFoo.Bar = Xamarin.Forms.Dependency.Get<IBar>();
    

    Otherwise you might want to look into another DI framework.