PolyhydraGames.Core.IOC.Autofac 2.0.0.2

dotnet add package PolyhydraGames.Core.IOC.Autofac --version 2.0.0.2
                    
NuGet\Install-Package PolyhydraGames.Core.IOC.Autofac -Version 2.0.0.2
                    
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="PolyhydraGames.Core.IOC.Autofac" Version="2.0.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="PolyhydraGames.Core.IOC.Autofac" Version="2.0.0.2" />
                    
Directory.Packages.props
<PackageReference Include="PolyhydraGames.Core.IOC.Autofac" />
                    
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 PolyhydraGames.Core.IOC.Autofac --version 2.0.0.2
                    
#r "nuget: PolyhydraGames.Core.IOC.Autofac, 2.0.0.2"
                    
#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 PolyhydraGames.Core.IOC.Autofac@2.0.0.2
                    
#: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=PolyhydraGames.Core.IOC.Autofac&version=2.0.0.2
                    
Install as a Cake Addin
#tool nuget:?package=PolyhydraGames.Core.IOC.Autofac&version=2.0.0.2
                    
Install as a Cake Tool

NuGet Version

Tags

  • ioc
  • dotnet
  • docs
  • testing
  • ui
  • game

PolyhydraGames.Core.IOC

A lightweight Inversion of Control (IOC) container library for .NET applications. Provides a simple dependency injection container with static instance access and fluent registration APIs.

Purpose

This library simplifies dependency injection in .NET applications by providing:

  • Static Instance Access: Access resolved services anywhere via IOC.Get<T>()
  • Fluent Registration: Easy-to-use extension methods for registering services
  • Multiple Container Support: Works with various IoC containers (Microsoft, Autofac, DryIoc)
  • Adapter Pattern: Adapter projects for popular IoC frameworks

Use Cases

  • Game Development: Manage service lifetimes in game engines (Unity, etc.)
  • Desktop Applications: Simple DI without complex framework requirements
  • Libraries: Provide DI support without forcing a specific container
  • Migration: Bridge between different IoC containers

Supported Target Frameworks

  • .NET 8.0
  • .NET 10.0

Installation

dotnet add package PolyhydraGames.Core.IOC

Or via Package Reference in your .csproj:

<PackageReference Include="PolyhydraGames.Core.IOC" Version="*" />

Validation

bash scripts/validate.sh

The repo validator restores, builds, tests, packs, and vulnerability-checks the IOC packages. Generated NuGet artifacts are written to artifacts/packages/.

Quick Start

1. Initialize the Container

// Initialize with your preferred container adapter
IOC.Initialize(new MicrosoftContainerAdapter());

2. Register Services

// Register a type as interface
container.RegisterType<MyService, IMyService>();

// Register as singleton
container.RegisterSingleton<MyService, IMyService>();

// Register an instance
container.RegisterInstance(myExistingInstance);

// Register self
container.RegisterType<MyService>();

3. Resolve Services

// Get service anywhere in your application
var service = IOC.Get<IMyService>();

// Get by type
var service2 = IOC.Get(typeof(IMyService));

Registration Extensions

The library provides fluent extension methods:

// Register type with interface
registration.RegisterType<MyService, IMyService>();

// Register as singleton
registration.RegisterSingleton<MyService, IMyService>();

// Register with all implemented interfaces
registration.RegisterType<MyService>()
    .AsImplementedInterfaces()
    .AsSingleton();

// Register self only
registration.RegisterType<MyService>()
    .AsSelf();

Adapters

This library includes adapters for popular IoC containers:

  • PolyhydraGames.Core.IOC.Microsoft - Microsoft.Extensions.DependencyInjection
  • PolyhydraGames.Core.IOC.Autofac - Autofac
  • PolyhydraGames.Core.IOC.DryIoc - DryIoc

API Reference

IOC Class

Method Description
IOC.Initialize(container) Initialize the static container instance
IOC.Get<T>() Resolve a service by type
IOC.Get<T>(Type type) Resolve a service with specific implementation type
IOC.Get(Type type) Resolve a service by type

Registration Extensions

Method Description
RegisterType<T, TInt>() Register type with interface
RegisterSingleton<T, TInt>() Register as singleton
RegisterInstance(obj) Register an existing instance
As<T>() Specify interface to register as
AsImplementedInterfaces() Register as all implemented interfaces
AsSingleton() Mark as singleton
AsSelf() Register type as itself

Documentation

Example: Full Configuration

public void ConfigureServices()
{
    // Initialize with Microsoft DI
    var services = new ServiceCollection();
    var adapter = new MicrosoftContainerAdapter(services);
    
    // Register services
    services.RegisterType<MyService, IMyService>()
        .AsSingleton();
    
    services.RegisterType<OtherService, IOtherService>();
    
    // Build and initialize
    var provider = services.BuildServiceProvider();
    IOC.Initialize(new MicrosoftContainerAdapter(provider));
}

// Later in your code...
public class MyComponent
{
    public void DoSomething()
    {
        var service = IOC.Get<IMyService>();
        service.DoWork();
    }
}

Migration Guide

Breaking Changes from Older Versions

  • Target framework baseline changed: packages target .NET 8.0 and .NET 10.0.
  • Registration model is adapter-first: initialize IOC with a concrete adapter before resolving services.
  • Fluent registration extensions are the preferred path over ad-hoc static/service-locator patterns.

Common Migration Scenarios

Scenario 1: Legacy static resolution to initialized adapter

Before:

var service = IOC.Get<IMyService>(); // may run before container is initialized

After:

var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
IOC.Initialize(new MicrosoftContainerAdapter(provider));

var service = IOC.Get<IMyService>();
Scenario 2: Manual singleton wiring to fluent registration

Before:

var myService = new MyService();
IOC.Initialize(new MicrosoftContainerAdapter(serviceProvider));
// custom/manual singleton wiring scattered across code

After:

var services = new ServiceCollection();
services.RegisterSingleton<MyService, IMyService>();
var provider = services.BuildServiceProvider();
IOC.Initialize(new MicrosoftContainerAdapter(provider));
Scenario 3: Switching adapters (Autofac/DryIoc/Microsoft)
// Autofac example
var builder = new ContainerBuilder();
var container = builder.Build();
IOC.Initialize(new AutofacContainerAdapter(container));

Use the same IOC.Get<T>() calls after initialization; only adapter setup changes.

Autofac Adapter Usage

Install

dotnet add package PolyhydraGames.Core.IOC.Autofac

Common Registration + Resolve Scenarios

using Autofac;
using PolyhydraGames.Core.IOC;

var registrations = new List<IIOCRegistration>
{
    // Interface + implementation
    new IOCRegistration
    {
        TInstance = typeof(MyService),
        TInterface = typeof(IMyService),
        Interfaces = true,
        Singleton = true
    },

    // Self registration
    new IOCRegistration
    {
        TInstance = typeof(LocalOnlyService),
        Self = true
    },

    // Prebuilt instance
    new IOCRegistration
    {
        Instance = new ConfigProvider(),
        TInterface = typeof(IConfigProvider),
        Interfaces = true,
        Singleton = true
    }
};

var ioc = new AutofacIOC();
ioc.Setup(registrations);
IOC.Initialize(ioc);

var service = IOC.Get<IMyService>();
var local = IOC.Get<LocalOnlyService>();

CI/CD

GitHub Actions now builds, tests, and publishes the IOC packages to GitHub Packages.

Configuration Options (AutofacIOC)

  • Self = true → register concrete type as itself (AsSelf())
  • Interfaces = true with TInterface set → register as explicit interface (As(interface))
  • Interfaces = true without TInterface → register all implemented interfaces (AsImplementedInterfaces())
  • Singleton = true → singleton lifetime (SingleInstance())
  • Instance set → register existing object instance
  • InstanceFunc set → register from factory delegate
  • Add Autofac.Module entries in the registration list to include full Autofac module configuration

Module-based Configuration

public sealed class MessagingModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<MyService>()
            .As<IMyService>()
            .SingleInstance();
    }
}

var ioc = new AutofacIOC();
ioc.Setup(new List<IIOCRegistration>
{
    new MessagingModule()
});

IOC.Initialize(ioc);

Assembly Scanning

Autofac supports scanning assemblies to register multiple types at once:

// Scan an assembly for implementations of a specific interface
var builder = new ContainerBuilder();

// Register all implementations of IHandler in the current assembly
builder.RegisterAssemblyTypes(typeof(MyHandler).Assembly)
    .Where(t => typeof(IHandler).IsAssignableFrom(t))
    .As<IHandler>()
    .SingleInstance();

// Register all public concrete classes as self
builder.RegisterAssemblyTypes(typeof(MyService).Assembly)
    .Where(t => t.IsClass && !t.IsAbstract)
    .AsSelf();

// Register with custom filtering
builder.RegisterAssemblyTypes(assembly)
    .Where(t => t.Name.EndsWith("Service"))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

// Build the container
var container = builder.Build();

Common Assembly Scanning Patterns:

Pattern Description
Where(t => typeof(IFoo).IsAssignableFrom(t)) Register implementations of interface
.AsImplementedInterfaces() Register as all implemented interfaces
.AsSelf() Register type as itself
.SingleInstance() Singleton lifetime
InstancePerDependency() Transient (default)
InstancePerLifetimeScope() Scoped lifetime

With IIOCRegistration:

You can include assembly scanning modules in your registration list:

public class ScanningModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(typeof(Program).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces()
            .SingleInstance();
    }
}

var ioc = new AutofacIOC();
ioc.Setup(new List<IIOCRegistration> { new ScanningModule() });
IOC.Initialize(ioc);

DryIoc Adapter Usage

Install

dotnet add package PolyhydraGames.Core.IOC.DryIoc

Common Registration + Resolve Scenarios

using DryIoc;
using PolyhydraGames.Core.IOC;

var registrations = new List<IIOCRegistration>
{
    // Interface + implementation (singleton)
    new IOCRegistration
    {
        TInstance = typeof(MyService),
        TInterface = typeof(IMyService),
        Interfaces = true,
        Singleton = true
    },

    // Self registration (transient)
    new IOCRegistration
    {
        TInstance = typeof(LocalOnlyService),
        Self = true
    },

    // Prebuilt instance
    new IOCRegistration
    {
        Instance = new ConfigProvider(),
        TInterface = typeof(IConfigProvider),
        Interfaces = true,
        Singleton = true
    },

    // Factory delegate registration
    new IOCRegistration
    {
        InstanceFunc = () => new TransientService(),
        TInstance = typeof(ITransientService),
        Singleton = false
    }
};

var container = new DryIocContainer();
container.Setup(registrations);
IOC.Initialize(container);

var service = IOC.Get<IMyService>();
var local = IOC.Get<LocalOnlyService>();

Configuration Options (DryIocContainer)

  • Self = true → register concrete type as itself (AsSelf())
  • Interfaces = true with TInterface set → register as explicit interface (As(interface))
  • Interfaces = true without TInterface → register all implemented interfaces (AsImplementedInterfaces())
  • Singleton = true → singleton lifetime (Reuse.Singleton)
  • Singleton = false → transient lifetime (default)
  • Instance set → register existing object instance (RegisterInstanceMany)
  • InstanceFunc set → register from factory delegate (RegisterDelegate)
  • DryModule entries → use DryIoc Container.RegisterMapping for module-based configuration

Module-based Configuration

public class DryMessagingModule : DryModule
{
    public void Load(IContainer container)
    {
        container.Register<IMyService, MyService>(reuse: Reuse.Singleton);
    }
}

var container = new DryIocContainer();
container.Setup(new List<IIOCRegistration>
{
    new DryMessagingModule()
});

IOC.Initialize(container);

Key Differences from Autofac

Feature Autofac DryIoc
Singleton syntax SingleInstance() Reuse.Singleton
Transient syntax InstancePerDependency() Default (no reuse)
Module base class Module Custom DryModule
Instance registration RegisterInstance() RegisterInstanceMany()

Microsoft.Extensions.DependencyInjection Adapter Usage

Install

dotnet add package PolyhydraGames.Core.IOC.Microsoft

Common Registration Patterns

The Microsoft adapter works directly with IServiceCollection:

using Microsoft.Extensions.DependencyInjection;
using PolyhydraGames.Core.IOC.Microsoft;

// Option 1: Use the adapter with ServiceCollection
var services = new ServiceCollection();
var adapter = new IocContainer();

// Add registrations via action delegates
adapter.Add(services =>
{
    services.AddSingleton<IMyService, MyService>();
    services.AddTransient<IOtherService, OtherService>();
    services.AddScoped<IThirdService, ThirdService>();
});

adapter.Finalize();
IOC.Initialize(adapter);

// Later resolve via IOC
var service = IOC.Get<IMyService>();

Using IIOCRegistration Pattern

using PolyhydraGames.Core.Interfaces;

var registrations = new List<IIOCRegistration>
{
    new IOCRegistration
    {
        TInstance = typeof(MyService),
        TInterface = typeof(IMyService),
        Interfaces = true,
        Singleton = true
    }
};

// Note: Microsoft adapter uses action-based registration pattern
// IIOCRegistration is converted via registration actions

Service Lifetimes

Lifetime Microsoft DI PolyhydraGames Core.IOC
Singleton AddSingleton<T, TImpl>() Singleton = true
Transient AddTransient<T, TImpl>() Singleton = false
Scoped AddScoped<T, TImpl>() Not directly supported

Configuration Options (IocContainer)

  • Add(registrations) → Add registration actions to be applied on Finalize()
  • Add(List<Action<IServiceCollection>>) → Batch add registration actions
  • Finalize() → Build the IServiceProvider from collected registrations
  • Provider → Access the underlying IServiceProvider

Integration with Microsoft.Extensions.DependencyInjection

public void ConfigureServices(IServiceCollection services)
{
    // Register framework services
    services.AddLogging();
    services.AddOptions();

    // Register your services
    services.AddSingleton<IMyService, MyService>();

    // Use with PolyhydraGames.IOC
    var adapter = new IocContainer(services);
    adapter.Finalize();
    IOC.Initialize(adapter);
}

Switching Between Adapters

One of the key benefits of using PolyhydraGames.Core.IOC is the ability to switch container implementations without changing your application code.

Comparison Matrix

Feature Microsoft Autofac DryIoc
NuGet Package Built-in PolyhydraGames.Core.IOC.Autofac PolyhydraGames.Core.IOC.DryIoc
Setup Complexity Low Medium Medium
Performance Good Very Good Excellent
Assembly Size N/A (built-in) ~200KB ~100KB
Best For ASP.NET Core apps Complex DI scenarios Performance-critical apps

Switching Example

// Microsoft (default for ASP.NET Core)
IOC.Initialize(new IocContainer(services));

// Autofac (for advanced module support)
var autofac = new AutofacIOC();
autofac.Setup(registrations);
IOC.Initialize(autofac);

// DryIoc (for performance)
var dryIoc = new DryIocContainer();
dryIoc.Setup(registrations);
IOC.Initialize(dryIoc);

// Your application code stays the same!
var service = IOC.Get<IMyService>(); // Works with any adapter

When to Use Each Adapter

Use Microsoft.Extensions.DependencyInjection when:

  • Building ASP.NET Core applications
  • You want minimal dependencies
  • You need tight integration with Microsoft ecosystem

Use Autofac when:

  • You need advanced DI features (modules, delegates, property injection)
  • You're migrating from Autofac
  • You want the richest feature set

Use DryIoc when:

  • Performance is critical
  • You want the smallest dependency footprint
  • You need fast resolution times

Building and Testing

# Restore packages
dotnet restore

# Build
dotnet build

# Run tests
dotnet test

License

MIT License - See LICENSE file for details.

Contributing

Contributions welcome! Please ensure tests pass before submitting PRs.

📖 Documentation

Detailed documentation can be found in the following sections:

Product Compatible and additional computed target framework versions.
.NET 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 is compatible.  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. 
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
2.0.0.2 108 10/16/2026
1.0.0.28 526 1/6/2024
1.0.0.27 292 8/24/2023
1.0.0.26 304 6/25/2023
1.0.0.25 358 4/12/2023
1.0.0.24 368 4/3/2023
1.0.0.23 485 1/6/2023
1.0.0.22 491 8/11/2022