Skip to content
Kevin Bost edited this page Dec 21, 2018 · 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.Build NuGet package to your project. PM> Install-Package AutoDI.Build
  2. 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.Build NuGet package your project. PM> Install-Package AutoDI.Build
  2. Mark constructor parameters (these should also specify a default value of null) as dependencies so they automatically get resolved.
using AutoDI;
public class MyExampleClass
{
    //This will automatically be populated when the constructor is invoked.
    [Dependency]
    private IOtherService OtherService { get; }

    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.

How it works

AutoDI injects code at the beginning of the constructor to automatically resolve any dependencies marked with the AutoDI.DependencyAttribute. Consider the code above, AutoDI injects code similar to the following into the constructor.

using AutoDI;
public class MyExampleClass
{
    //This will automatically be populated when the constructor is invoked.
    [Dependency]
    private IOtherService OtherService { get; }

    public MyExampleClass([Dependency]IService service = null)
    {
        if (service == null) serivce = GlobalDI.GetService<IService>(new object[0]);
        if (OtherService == null) OtherService = GlobalDI.GetService<IOtherService>(new object[0]);

        if (service == null) throw new ArgumentNullException(nameof(service));
    }
}

The dependencies are resolved prior to the base constructor being invoked. This means that you can then pass the values into the base constructor.