Outils pour utilisateurs

Outils du site


developpement:dotnet:msioc

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
developpement:dotnet:msioc [2023/05/11 19:52] sgariepydeveloppement:dotnet:msioc [2023/06/19 18:43] (Version actuelle) – [Exemple] sgariepy
Ligne 1: Ligne 1:
-====== IoC ======+====== Inversion of Control ======
  
-Recherche "console background service"+En utilisant le package ''Microsoft.Extensions.DependencyInjection''.
  
 +Documenté dans le contexte de .NET Core 7.
  
 Lifetimes Lifetimes
Ligne 18: Ligne 19:
     * Instances cannot be shared accoss different components in an application     * Instances cannot be shared accoss different components in an application
     * Ideal for retrieving information from a database or API     * Ideal for retrieving information from a database or API
 +
 +
 +
 +
 +===== Example de "container" =====
 +
 +Ceci n'est pas exactement le container, mais la configuration d'un container.  Ça peut être utilisé dans une couche DDD, par exemple ''Application'' ou ''Infrastructure''.
 +
 +
 +<code csharp>
 +using Microsoft.Extensions.DependencyInjection;
 +
 +namespace Infrastructure;
 +
 +public static class DependencyInjection
 +{
 +    public static IServiceCollection AddInfrastructure(this IServiceCollection services)
 +    {
 +        services.AddSingleton<IMqttService, MqttService>();
 +
 +        return services;
 +    }
 +}
 +</code>
 +
 +Ensuite avec le ''builder'' (Dans ''Program.cs'', on peut faire:
 +
 +<code csharp>
 +builder.Services
 +    .AddApplication()
 +    .AddInfrastructure();
 +</code>
 +
 +====== Hosted Service ======
 +
 +
 +  * Permet d'exécuter des tâches en arrière-plan
 +  * Configuré dans ASP.NET Core ou via un modèle Worker Service
 +  * Worker Service sont faits pour des tâches en arrière-plan
 +  * Utiliser ASP.NET Core pour ajouter un service //hosted//
 +
 +
 +
 +
 +<code csharp>
 +using Microsoft.Extensions.Hosting;
 +
 +public class CustomHostedService: IHostedService, IDisposable
 +{
 +    public CustomHostedService()
 +    {
 +        Console.WriteLine("ctor");
 +    }
 +    
 +    public async Task StartAsync(CancellationToken cancellationToken)
 +    {
 +        Console.WriteLine("Start Async");
 +
 +        await Task.Delay(1000, cancellationToken);
 +    }
 +    
 +    public Task StopAsync(CancellationToken cancellationToken)
 +    {
 +        return Task.CompletedTask;
 +    }
 +}
 +</code>
 +
 +
 +Dans la configuration du _container_:
 +
 +<code csharp>
 +services
 +    .AddTransient<IHostedService, CustomHostedService>();
 +</code>
 +
 +_Injecter_ le service manuellement:
 +
 +<code csharp>
 +app.Services.GetService(typeof(CustomHostedService));
 +</code>
 +
 +
 +===== Background Service =====
 +
 +
 +<code csharp>
 +using Microsoft.Extensions.Hosting;
 +
 +public class CustomBackgroundService: BackgroundService
 +{
 +    public CustomBackgroundService()
 +    {
 +        Console.WriteLine("ctor");
 +    }
 +    
 +    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 +    {
 +        await Task.Delay(1000, stoppingToken);
 +    }
 +}
 +</code>
 +
 +
 +Dans la configuration du _container_:
 +
 +<code csharp>
 +services
 +    .AddHostedService<CustomBackgroundService>();
 +</code>
 +
 +_Injecter_ le service manuellement:
 +
 +<code csharp>
 +app.Services.GetService(typeof(CustomBackgroundService));
 +</code>
 +
 +==== Exemple ====
 +
 +
 +<code csharp>
 +protected override async Task ExecuteTask(CancellationToken cancellationToken)
 +{
 +
 +    while (!cancellationToken.IsCancellationRequested)
 +    {
 +        using (var scope = _serviceProvider.CreateScope())
 +        {
 +            var productService = scope.ServiceProvider.GetService<IProductService>();
 +        
 +        }
 +    }
 +}
 +</code>
 +
 +====== Exemple exécutable dans LinqPad 7 ======
 +
 +Language: C# Program, .NET 7.0
 +
 +<code csharp>
 +void Main()
 +{
 + string[] args = new string[0];
 +
 + using IHost host = Host.CreateDefaultBuilder(args)
 + .ConfigureServices((_, services) =>
 + services
 + .AddSingleton<ISimpleService, SimpleService>()
 + .AddSingleton<BasicService>()
 + )
 + .Build();
 +
 + using IServiceScope serviceScope = host.Services.CreateScope();
 + IServiceProvider provider = serviceScope.ServiceProvider;
 +
 + BasicService basicService = provider.GetService<BasicService>();
 +
 + // host.Run();
 +
 + Console.WriteLine("End of program");
 +}
 +
 +#region Services
 +
 +public class BasicService
 +{
 + private readonly ISimpleService _simpleService;
 +
 + public BasicService(
 + ISimpleService simpleService)
 + {
 + _simpleService = simpleService;
 +
 + SetupService();
 + }
 +
 +
 + private void SetupService()
 + {
 + _simpleService.SayHello();
 + }
 +}
 +
 +public interface ISimpleService {
 + public void SayHello();
 +}
 +
 +public class SimpleService: ISimpleService
 +{
 + private readonly ISimpleService _simpleService;
 +
 + public SimpleService() {}
 +
 + public void SayHello()
 + {
 + Console.WriteLine("Hello");
 + }
 +}
 +
 +#endregion
 +</code>
 + 
 +
 +
 +
 +
 +
 +
 +
 +
  
  
  
developpement/dotnet/msioc.1683827530.txt.gz · Dernière modification : 2023/05/11 19:52 de sgariepy