-
Notifications
You must be signed in to change notification settings - Fork 17
ResolvingDependencies
There are several ways to resolve dependencies using AutoDI.
This is typically used with constructors but it works with any method. The parameter must be decorated with the [AutoDI.DependencyAttribute]
. It is expected that the parameter also be marked as optional (this is not required, but will raise a warning).
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));
}
}
Or using any method
using AutoDI;
public class MyExampleClass
{
public void DoThings([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));
}
}
Property injection requires properties to be decorated with [AutoDI.DependencyAttribute]
. The property must be an auto-implemented property (also supports read-only auto properties) or have a setter. Because properties are resolved when the instance constructor is called, the setter can be primave. The property can also be a getter-only auto-property
using AutoDI;
public class MyExampleClass
{
[Dependency]
public IService Service { get; }
private IService2 _Service2;
[Dependency]
private IService2 Service2
{
get => _Service2;
set
{
if (value == _Service2) return;
_Service2 = value ?? throw new ArgumentNullException(nameof(value));
}
}
public MyExampleClass()
{
//A constructor is not strickly needed.
//Use properties however you want. You can even perform validation.
if (Service == null) throw new Exception(nameof(Service) + " is null");
}
}
First you must get an IServiceProvider instance. You can use one of the above methods, or you can get the root IServiceProvider using one of the AutoDI static methods.
//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);
Then use the IServiceProvider
to resolve the dependency:
IService service = provider.GetService<IService>();