Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork3
📦 nanoFramework.DependencyInjection library for .NET nanoFramework
License
nanoframework/nanoFramework.DependencyInjection
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Provides Dependency Injection (DI) for Inversion of Control (IoC) between classes and their dependencies built for .NET nanoFramework.
Component | Build Status | NuGet Package |
---|---|---|
nanoFramework.DependencyInjection |
Dependency Injection Unit Tests
A Dependency Injection (DI) Container provides functionality and automates many of the tasks involved in Object Composition, Interception, and Lifetime Management. It's an engine that resolves and manages object graphs. These DI Containers depend on the static information compiled into all classes. Then using reflection they can analyze the requested class and figure out which Dependencies are required.
This API mirrors as close as possible the official .NETDependencyInjection. Exceptions are mainly derived from the lack of generics support in .NET nanoFramework.
The .NET nanoFrameworkGeneric Host provides convenience methods for creating dependency injection (DI) application containers with preconfigured defaults.
Creating a dependency injection container required three basic components.
- Object Composition - A object composition defining a set of objects to create and couple.
- Registering Services - Define an instance of the ServiceCollection and register the object composition with a specific service lifetime.
- Service Provider - Creating a service provider to retrieve the object.
Define an object composition to create and couple.
Note: You can not currently define your objects as 'struct' or include array type parameters (ie. byte[] bytes) as constructor parameters. Doing so will create a null execption when trying to activate object.
publicclassRootObject{publicintOne{get;}publicstringTwo{get;}publicServiceObjectServiceObject{get;protectedset;}publicRootObject(ServiceObjectserviceObject){ServiceObject=serviceObject;}// constructor with the most parameters will be used for activationpublicRootObject(ServiceObjectserviceObject,intone,stringtwo){ServiceObject=serviceObject;One=one;Two=two;}}publicclassServiceObject{publicstringThree{get;set;}}
Create a Service Collection and register singleton or transient type services to the collection.
varserviceProvider=newServiceCollection().AddSingleton(typeof(ServiceObject)).AddSingleton(typeof(RootObject)).BuildServiceProvider();
Create a Service Provider to access or update an object.
varservice=(RootObject)serviceProvider.GetService(typeof(RootObject));service.ServiceObject.Three="3";
Create a scoped Service Provider providing convient access to crate and distroy scoped object.
varserviceProvider=newServiceCollection().AddScoped(typeof(typeof(ServiceObject)).BuildServiceProvider();using(varscope=serviceProvider.CreateScope()){varservice=scope.ServiceProvider.GetServices(typeof(ServiceObject));service.ServiceObject.Three="3";}
An instance of an object can be created by calling its constructor with any dependencies resolved through the service provider. Automatically instantiate a type with constructor arguments provided from an IServiceProvider without having to register the type with the DI Container.
varinstance=(RootObject)ActivatorUtilities.CreateInstance(serviceProvider,typeof(RootObject),1,"2");Debug.WriteLine($"One:{instance.One}");Debug.WriteLine($"Two:{instance.Two}");Debug.WriteLine($"Three:{instance.ServiceObject.Three}");Debug.WriteLine($"Name:{instance.ServiceObject.GetType().Name}");
A check is performed to ensure that all services registered with the container can actually be created. This can be particularly useful during development to fail fast and allow developers to fix the issue. Validate on build is configured false by default.
varserviceProvider=newServiceCollection().AddSingleton(typeof(IServiceObject),typeof(ServiceObject)).BuildServiceProvider(newServiceProviderOptions(){ValidateOnBuild=true});
A check verifying that scoped services never gets resolved from root provider. Validate on build is configured false by default.
varserviceProvider=newServiceCollection().AddSingleton(typeof(IServiceObject),typeof(ServiceObject)).BuildServiceProvider(newServiceProviderOptions(){ValidateScopes=true});
usingSystem;usingSystem.Device.Gpio;usingSystem.Threading;usingnanoFramework.Logging.Debug;usingnanoFramework.DependencyInjection;usingMicrosoft.Extensions.Logging;nanoFramework.DiApplication{publicclassProgram{publicstaticvoidMain(){varservices=ConfigureServices();varapplication=(Application)services.GetRequiredService(typeof(Application));application.Run();}privatestaticServiceProviderConfigureServices(){returnnewServiceCollection().AddSingleton(typeof(Application)).AddSingleton(typeof(IHardwareService),typeof(HardwareService)).AddSingleton(typeof(ILoggerFactory),typeof(DebugLoggerFactory)).BuildServiceProvider();}}internalclassApplication{privatereadonlyILogger_logger;privatereadonlyIHardwareService_hardware;privatereadonlyIServiceProvider_provider;publicApplication(IServiceProviderprovider,IHardwareServicehardware,ILoggerFactoryloggerFactory){_provider=provider;_hardware=hardware;_logger=loggerFactory.CreateLogger(nameof(Application));_logger.LogInformation("Initializing application...");}publicvoidRun(){varledPin=23;// Set pin number to blink 15=ESP32; 23=STM32_logger.LogInformation($"Started blinking led on pin{ledPin}.");_hardware.StartBlinking(ledPin);}}internalinterfaceIHardwareService{publicvoidStartBlinking(intledPin){}}internalclassHardwareService:IHardwareService,IDisposable{privateThread_thread;privatereadonlyILogger_logger;privatereadonlyGpioController_gpioController;publicHardwareService(){_gpioController=newGpioController();varloggerFactory=newDebugLoggerFactory();_logger=loggerFactory.CreateLogger(nameof(HardwareService));}publicHardwareService(ILoggerFactoryloggerFactory){_gpioController=newGpioController();_logger=loggerFactory.CreateLogger(nameof(HardwareService));}publicvoidStartBlinking(intledPin){GpioPinled=_gpioController.OpenPin(ledPin,PinMode.Output);led.Write(PinValue.Low);_thread=newThread(()=>{while(true){Thread.Sleep(2000);led.Write(PinValue.High);_logger.LogInformation("Led status: on");Thread.Sleep(2000);led.Write(PinValue.Low);_logger.LogInformation("Led status: off");}});_thread.Start();}publicvoidDispose(){_gpioController.Dispose();}}}
For documentation, providing feedback, issues and finding out how to contribute please refer to theHome repo.
Join our Discord communityhere.
The list of contributors to this project can be found atCONTRIBUTORS.
ThenanoFramework Class Libraries are licensed under theMIT license.
This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behaviour in our community.For more information see the.NET Foundation Code of Conduct.
This project is supported by the.NET Foundation.
About
📦 nanoFramework.DependencyInjection library for .NET nanoFramework
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Contributors8
Uh oh!
There was an error while loading.Please reload this page.