Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

📦 nanoFramework.DependencyInjection library for .NET nanoFramework

License

NotificationsYou must be signed in to change notification settings

nanoframework/nanoFramework.DependencyInjection

Repository files navigation

Quality Gate StatusReliability RatingLicenseNuGet#yourfirstprDiscord

nanoFramework logo


Welcome to the .NET nanoFramework Dependency Injection Library repository

Provides Dependency Injection (DI) for Inversion of Control (IoC) between classes and their dependencies built for .NET nanoFramework.

Build status

ComponentBuild StatusNuGet Package
nanoFramework.DependencyInjectionBuild StatusNuGet

Samples

Dependency Injection Samples

Dependency Injection Unit Tests

Dependency Injection Container

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.

Usage

Service Collection

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.

Object Composition

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;}}

Registering Services

Create a Service Collection and register singleton or transient type services to the collection.

varserviceProvider=newServiceCollection().AddSingleton(typeof(ServiceObject)).AddSingleton(typeof(RootObject)).BuildServiceProvider();

Service Provider

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";}

Activator Utilities

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}");

Validate On Build

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});

Validate Scopes

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});

Example Application Container

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();}}}

Feedback and documentation

For documentation, providing feedback, issues and finding out how to contribute please refer to theHome repo.

Join our Discord communityhere.

Credits

The list of contributors to this project can be found atCONTRIBUTORS.

License

ThenanoFramework Class Libraries are licensed under theMIT license.

Code of Conduct

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.

.NET Foundation

This project is supported by the.NET Foundation.

About

📦 nanoFramework.DependencyInjection library for .NET nanoFramework

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

  •  

Contributors8

Languages


[8]ページ先頭

©2009-2025 Movatter.jp