StableDiffusionNet.DependencyInjection 1.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package StableDiffusionNet.DependencyInjection --version 1.1.0
                    
NuGet\Install-Package StableDiffusionNet.DependencyInjection -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="StableDiffusionNet.DependencyInjection" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="StableDiffusionNet.DependencyInjection" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="StableDiffusionNet.DependencyInjection" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add StableDiffusionNet.DependencyInjection --version 1.1.0
                    
#r "nuget: StableDiffusionNet.DependencyInjection, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package StableDiffusionNet.DependencyInjection@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=StableDiffusionNet.DependencyInjection&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=StableDiffusionNet.DependencyInjection&version=1.1.0
                    
Install as a Cake Tool

StableDiffusionNet.DependencyInjection

Расширения для Microsoft.Extensions.DependencyInjection для работы с StableDiffusionNet.Core.

Особенности

  • 🔌 Microsoft.Extensions.DependencyInjection: полная интеграция с DI контейнером
  • 📊 Microsoft.Extensions.Logging: автоматическая интеграция с логированием
  • ⚙️ IOptions Pattern: конфигурация через IOptions<T>
  • 🏭 IHttpClientFactory: управление HttpClient через фабрику
  • 🔄 Все возможности Core: полный доступ к функционалу StableDiffusionNet.Core

Установка

dotnet add package StableDiffusionNet.DependencyInjection

Пакет автоматически установит StableDiffusionNet.Core как зависимость.

Или через NuGet Package Manager:

Install-Package StableDiffusionNet.DependencyInjection

Быстрый старт

Простая регистрация

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using StableDiffusionNet.DependencyInjection.Extensions;

var services = new ServiceCollection();

// Добавление логирования (опционально, но рекомендуется)
services.AddLogging(builder => builder.AddConsole());

// Регистрация StableDiffusion клиента (простейший вариант)
services.AddStableDiffusion("http://localhost:7860");

var serviceProvider = services.BuildServiceProvider();
var client = serviceProvider.GetRequiredService<IStableDiffusionClient>();

Расширенная конфигурация

services.AddStableDiffusion(options =>
{
    options.BaseUrl = "http://localhost:7860";
    options.TimeoutSeconds = 600;
    options.RetryCount = 5;
    options.RetryDelayMilliseconds = 2000;
    options.ApiKey = "your-api-key";
    options.EnableDetailedLogging = true; // Только для отладки!
});

ASP.NET Core Integration

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Регистрация из конфигурации
builder.Services.AddStableDiffusion(options =>
{
    builder.Configuration.GetSection("StableDiffusion").Bind(options);
});

var app = builder.Build();
// appsettings.json
{
  "StableDiffusion": {
    "BaseUrl": "http://localhost:7860",
    "TimeoutSeconds": 300,
    "RetryCount": 3
  }
}

Использование в контроллерах

using Microsoft.AspNetCore.Mvc;
using StableDiffusionNet.Interfaces;
using StableDiffusionNet.Models.Requests;

[ApiController]
[Route("api/[controller]")]
public class ImageGenerationController : ControllerBase
{
    private readonly IStableDiffusionClient _sdClient;
    private readonly ILogger<ImageGenerationController> _logger;

    public ImageGenerationController(
        IStableDiffusionClient sdClient,
        ILogger<ImageGenerationController> logger)
    {
        _sdClient = sdClient;
        _logger = logger;
    }

    [HttpPost("generate")]
    public async Task<IActionResult> Generate([FromBody] TextToImageRequest request)
    {
        try
        {
            var response = await _sdClient.TextToImage.GenerateAsync(request);
            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Image generation failed");
            return StatusCode(500, "Generation failed");
        }
    }
}

Использование отдельных сервисов

Вы также можете внедрять отдельные сервисы:

public class MyService
{
    private readonly ITextToImageService _textToImage;
    private readonly IModelService _models;
    
    public MyService(
        ITextToImageService textToImage,
        IModelService models)
    {
        _textToImage = textToImage;
        _models = models;
    }
    
    public async Task DoSomething()
    {
        var models = await _models.GetModelsAsync();
        // ...
    }
}

Безопасность API ключей

Важно: Никогда не храните API ключи в коде или публичных репозиториях!

User Secrets (для разработки)

dotnet user-secrets set "StableDiffusion:ApiKey" "your-secret-key"
services.AddStableDiffusion(options =>
{
    options.ApiKey = builder.Configuration["StableDiffusion:ApiKey"];
});

Переменные окружения

# Windows PowerShell
$env:SD_API_KEY="your-secret-key"

# Linux/Mac
export SD_API_KEY="your-secret-key"
services.AddStableDiffusion(options =>
{
    options.ApiKey = Environment.GetEnvironmentVariable("SD_API_KEY");
});

Azure Key Vault (для продакшена)

var keyVaultUri = new Uri(builder.Configuration["KeyVaultUri"]);
builder.Configuration.AddAzureKeyVault(keyVaultUri, new DefaultAzureCredential());

Логирование

Библиотека автоматически интегрируется с Microsoft.Extensions.Logging:

// Настройка логирования
builder.Services.AddLogging(builder =>
{
    builder.AddConsole();
    builder.AddDebug();
    builder.SetMinimumLevel(LogLevel.Information);
});

Логи включают:

  • Информацию о запросах и ответах
  • Ошибки и исключения
  • Retry попытки
  • Прогресс операций

Внимание: Опция EnableDetailedLogging может логировать чувствительные данные (промпты, base64 изображения). Используйте только для отладки в безопасном окружении!

Доступные опции

Опция Тип По умолчанию Описание
BaseUrl string "http://localhost:7860" Базовый URL API
TimeoutSeconds int 300 Таймаут запросов в секундах
RetryCount int 3 Количество повторов при ошибке
RetryDelayMilliseconds int 1000 Задержка между повторами в мс
ApiKey string? null API ключ (если требуется)
EnableDetailedLogging bool false Детальное логирование (только для отладки!)

Нужен lightweight вариант без DI?

Если вам не нужна интеграция с Dependency Injection, используйте базовый пакет StableDiffusionNet.Core:

dotnet add package StableDiffusionNet.Core
var client = StableDiffusionClientBuilder.CreateDefault("http://localhost:7860");

Лицензия

MIT License

Ссылки

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.5 169 10/28/2025
1.1.4 164 10/27/2025
1.1.3 158 10/26/2025
1.1.2 160 10/26/2025
1.1.1 149 10/26/2025
1.1.0 152 10/26/2025

See CHANGELOG.md for details