2

I am using Autofac in Xamarin Android app, the container returns null object reference because nothing is assigned to the container until a block of code is ran. However, i'm not sure how to make the block of code actually run. This is probably a simple issue but just on case, here is use of the container:

public void AddToCartnBtn_Click(object sender, EventArgs e)
    {
        using (var scope = App.Container.BeginLifetimeScope())
        {
            var basket = scope.Resolve<IBasket>();
            basket.AddToBasket(clickedItem);
            scope.Dispose();
        }
    }

And here is my container / autofac setup:

public class App
{
    public static IContainer Container { get; set; }

    public App()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<ProductList>().As<IProductList>();
        builder.RegisterInstance(new Basket()).As<IBasket>();

        Container = builder.Build();
    }
}
Travis Illig
  • 23,195
  • 2
  • 62
  • 85
Micheal
  • 21
  • 3
  • 1
    Since the App is never instantiated the constructor is never called and the container is never build/assigned. An easy fix is to make the constructor static `static App()` which ensures the `Container` member is initialized before being called. – Lennart Stoop Jul 25 '18 at 12:34
  • Off topic: calling `scope.Dispose()` is not necessary as this is already handled by the [using statement](https://stackoverflow.com/questions/17357258/does-using-statement-always-dispose-the-object) when it completes – Lennart Stoop Jul 25 '18 at 12:41
  • Ill give that a go, thanks for your help! Also, good shout , didn't think of that. Thanks – Micheal Jul 25 '18 at 13:05

0 Answers0