Xamarin.Forms Projects
上QQ阅读APP看书,第一时间看更新

Wiring up a dependency injection through Autofac

Earlier, we discussed the dependency injection pattern, which states that all dependencies, such as the repositories and view models, must be passed through the constructor of the class. This has several benefits:

  • It increases the readability of the code, since we can quickly determine all external dependencies
  • It makes dependency injection possible
  • It makes unit testing possible by mocking classes
  • We can control the lifetime of an object by specifying whether it should be a singleton or a new instance for each resolution

Dependency injection is a pattern that lets us determine at runtime which instance of an object should be passed to a constructor when an object is created. We do this by defining a container where we register all the types of a class. We let the framework that we are using resolve any dependencies between them. Let's say that we ask the container for a MainView. The container takes care of resolving the MainViewModel and any dependencies that the class has.

To set this up, we need to reference a library called Autofac. There are other options out there, so feel free to switch to one that better fits your needs. We also need an entry point to resolve the types into instances. To do this, we will define a bare-bones Resolver class. To wrap it all up, we need a bootstrapper that we will call to initialize the dependency injection configuration.