-
Notifications
You must be signed in to change notification settings - Fork 17
Quick Start
Kevin B edited this page Sep 22, 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.
In this setup all of the dependencies are resolved with the global application IServiceProvider
.
- Add the AutoDI.Fody package your project. This will also include the AutoDI nuget package.
- 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 it.
- 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>
- 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));
}
}
- Done. AutoDI will now automatically generate a DI container for your at compile time, and will be used to resolve the dependencies.
For Xamarin.Android projects you will need to manually inject the container (see details below).
- Add the AutoDI.Fody nuget package to your project. This will also include the AutoDI nuget package.
- 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 it.
- 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>
- Get the IServiceProvider. At this point it is up to you how to best utilize it in your application.
IServiceProvider provider = GlobalDI.GetService<IServiceProvider>(new object[0]);
//Or from the entry assembly
IServiceProvider provider = DI.GetGlobalServiceProvider(GetType().Assembly);
- Use the IServiceProvider to resolve your dependencies.
MyThing thing = provider.GetService<MyThing>();