You can either use AutoDI with optional constructor parameters or simply get ahold of the IServiceProvider and use it to resolve dependencies.
AutoDI using IServiceProviderPM> Install-Package AutoDI.Build
//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);
IService service = provider.GetService<IService>();AutoDI using optional constructor parameters
In this setup all of the dependencies are resolved with the global application IServiceProvider
.
PM> Install-Package AutoDI.Build
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)); } }
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4