πŸ“¦ nanoFramework.Hosting library for .NET nanoFramework
ΠŸΠ΅Ρ€Π΅ΠΉΡ‚ΠΈ ΠΊ Ρ„Π°ΠΉΠ»Ρƒ
github-actions[bot] 4eeb11669f
Update 1 NuGet dependencies
***NO_CI***
2024-11-19 00:39:04 +00:00
.github/workflows Updated project folder 2022-07-10 09:09:35 -07:00
assets Work CI-CD 2022-07-15 09:44:01 +01:00
config Work CI-CD 2022-07-15 09:44:01 +01:00
nanoFramework.Hosting Update 1 NuGet dependencies 2024-10-19 01:36:44 +01:00
tests Update 1 NuGet dependencies 2024-11-19 00:39:04 +00:00
.gitattributes Initial commit 2022-06-18 13:16:40 -07:00
.github_changelog_generator Updated project folder 2022-07-10 09:09:35 -07:00
.gitignore Initial commit 2022-06-18 13:16:40 -07:00
CHANGELOG.md Update CHANGELOG for v1.0.40 2023-11-10 00:40:44 +00:00
LICENSE.md Initial commit 2022-06-18 13:16:40 -07:00
NuGet.Config Updated project folder 2022-07-10 09:09:35 -07:00
README.md Update README 2022-07-15 09:13:53 +01:00
azure-pipelines.yml Work CI-CD 2024-01-20 20:31:57 +00:00
nanoFramework.Hosting.sln Miscellaneous changes from code review 2022-07-14 11:50:36 +01:00
nanoframework.Hosting.nuspec Update 3 NuGet dependencies 2023-11-10 00:34:32 +00:00
template.vssettings Initial commit 2022-06-18 13:16:40 -07:00
version.json Work CI-CD 2022-12-28 11:06:29 +00:00

README.md

Quality Gate Status Reliability Rating License NuGet #yourfirstpr Discord

nanoFramework logo


Welcome to the .NET nanoFramework Generic Host Library repository

The .NET nanoFramework Generic Host provides convenience methods for creating dependency injection (DI) application containers with preconfigured defaults.

Build status

Component Build Status NuGet Package
nanoFramework.Hosting Build Status NuGet

Samples

Hosting Samples

Hosting Unit Tests

Generic Host

A Generic Host configures a DI application container as well as provides services in the DI container which handle the the application lifetime. When a host starts it calls Start() on each implementation of IHostedService registered in the service container's collection of hosted services. In the application container all IHostedService object that inherent BackgroundService or SchedulerService have their ExecuteAsync() methods called.

This API mirrors as close as possible the official .NET Generic Host.

using nanoFramework.Hosting;
using nanoFramework.DependencyInjection;

namespace Hosting
{
    public class Program
    {
        public static void Main()
        {
            IHost host = CreateHostBuilder().Build();
            
            // starts application and blocks the main calling thread 
            host.Run();
        }

        public static IHostBuilder CreateHostBuilder() =>
            Host.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    services.AddSingleton(typeof(BackgroundQueue));
                    services.AddHostedService(typeof(SensorService));
                    services.AddHostedService(typeof(DisplayService));
                });
    }
}

IHostedService interface

When you register an IHostedService the host builder will call the Start() and Stop() methods of IHostedService during application start and stop respectively. You can create multiple implementations of IHostedService and register them using the ConfigureService() method in the DI container. All hosted services will be started and stopped along with the application.

public class CustomService : IHostedService
{
    public void Start() { }

    public void Stop() { }
}

BackgroundService base class

Provides a base class for implementing a long running IHostedService. The method ExecuteAsync() is called asynchronously to run the background service. Your implementation of ExecuteAsync() should finish promptly when the CancellationRequested is fired in order to gracefully shut down the service.

public class SensorService : BackgroundService
{
    protected override void ExecuteAsync()
    {
        while (!CancellationRequested)
        {
            // to allow other threads time to process include 
            // at least one millsecond sleep in loop
            Thread.Sleep(1);
        }
    }
}

SchedulerService base class

Provides a base class for implementing a scheduled Timer running IHostedServce. The timer triggers at a specified time and interval the ExecuteAsync() method. The timer is disabled on Stop() and disposed when the service container is disposed.

public class DisplayService : SchedulerService
{
    // represents a timer control that involks ExecuteAsync at a 
    // specified interval of time repeatedly
    public DisplayService() : base(TimeSpan.FromSeconds(1)) {}

    protected override void ExecuteAsync(object state)
    {   
    }
}

IServiceCollection extensions method

Extending IServiceCollection is a pretty straightforward way to add additional features to the application container.

public static IServiceCollection AddLogging(this IServiceCollection services, LogLevel level)
{
    if (services == null)
    {
        throw new ArgumentNullException();
    }

    var loggerFactory = new DebugLoggerFactory();
    LogDispatcher.LoggerFactory = loggerFactory;

    var logger = (DebugLogger)loggerFactory.GetCurrentClassLogger();
    logger.MinLogLevel = level;

    // using TryAdd prevents duplicate logging objects if AddLogging() 
    // is added more then once to ConfigureServices
    services.TryAdd(new ServiceDescriptor(typeof(ILogger), logger));
    services.TryAdd(new ServiceDescriptor(typeof(ILoggerFactory), loggerFactory));

    return services;
}

The extension can then be registered like this:

public static IHostBuilder CreateHostBuilder() =>
    Host.CreateDefaultBuilder()
        .ConfigureServices(services =>
        {
            services.AddLogging(LogLevel.Debug);
            services.AddSingleton(typeof(LoggingService));
        });

And used like this:

public class LoggingService : IHostedService
{
    private ILogger Logger { get; set; }

    public LoggingService(ILogger logger)
    {
        Logger = logger;
    }

    public void Start()
    {
        Logger.Log(LogLevel.Information, new EventId(10, "Start"), "Logging started", null);
    }

    public void Stop()
    {
        Logger.Log(LogLevel.Information, new EventId(11, "Stop"), "Logging stopped", null);
    }
}

Validate On Build

The default builder enables DI validation when the debugger is attached. This 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 issues. The setting can be modified by using the UseDefaultServiceProvider() method.

public static IHostBuilder CreateHostBuilder() =>
    Host.CreateDefaultBuilder()
        .UseDefaultServiceProvider(options =>
        {
            options.ValidateOnBuild = false;
        });

Feedback and documentation

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

Join our Discord community here.

Credits

The list of contributors to this project can be found at CONTRIBUTORS.

License

The nanoFramework Class Libraries are licensed under the MIT 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.