Skip to content
Kevin B edited this page Oct 5, 2017 · 12 revisions

You can either use AutoDI with optional constructor parameters or simply get ahold of the IServiceProvider and use it to resolve dependencies.

AutoDI using IServiceProvider

  1. Add the AutoDI.Fody nuget package to your project. PM> Install-Package Portable.Licensing
  2. Ensure there is a FodyWeavers.xml file at the root of your project (its Build Action should be None). For many project types it will be added for you, but for some you will need to manually add this file.
  3. Add AutoDI to the list of Weavers to run. A simple example file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <AutoDI />
</Weavers>
  1. Get an IServiceProvider instance. At this point it is up to you how to best utilize it in your application.
//The GlobalDI service provider is set when AutoDI is initialized
IServiceProvider provider = GlobalDI.GetService<IServiceProvider>(new object[0]);
//Or from the entry assembly
IServiceProvider provider = DI.GetGlobalServiceProvider(GetType().Assembly);
  1. Use the IServiceProvider to resolve your dependencies.
IService service = provider.GetService<IService>();

AutoDI using optional constructor parameters

In this setup all of the dependencies are resolved with the global application IServiceProvider.

  1. Add the AutoDI.Fody package your project. PM> Install-Package Portable.Licensing
  2. Ensure there is a FodyWeavers.xml file at the root of your project (its Build Action should be None). For many project types it will be added for you, but for some you will need to manually add this file.
  3. Add AutoDI to the list of Weavers to run. A simple example file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <AutoDI />
</Weavers>
  1. Mark constructor parameters (these should also specify a default value of null) as dependencies so they automatically get resolved.
using AutoDI;
public class MyExampleClass
{
    public MyExampleClass([Dependency]IService service = null)
    {
        //Use service however you want. It will automatically be injected for you.
        //You can even check it for null, just to make sure it gets injected.
        if (service == null) throw new ArgumentNullException(nameof(service));
    }
}
  1. Done. AutoDI will now automatically generate a DI container for your at compile time, and will be used to resolve the dependencies.