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
<PackageReference Include="PolyhydraGames.Core.IOC.Autofac" Version="2.0.0.2" />
<PackageVersion Include="PolyhydraGames.Core.IOC.Autofac" Version="2.0.0.2" />
<PackageReference Include="PolyhydraGames.Core.IOC.Autofac" />
paket add PolyhydraGames.Core.IOC.Autofac --version 2.0.0.2
#r "nuget: PolyhydraGames.Core.IOC.Autofac, 2.0.0.2"
#:package PolyhydraGames.Core.IOC.Autofac@2.0.0.2
#addin nuget:?package=PolyhydraGames.Core.IOC.Autofac&version=2.0.0.2
#tool nuget:?package=PolyhydraGames.Core.IOC.Autofac&version=2.0.0.2
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.DependencyInjectionPolyhydraGames.Core.IOC.Autofac- AutofacPolyhydraGames.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.0and.NET 10.0. - Registration model is adapter-first: initialize
IOCwith 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 = truewithTInterfaceset → register as explicit interface (As(interface))Interfaces = truewithoutTInterface→ register all implemented interfaces (AsImplementedInterfaces())Singleton = true→ singleton lifetime (SingleInstance())Instanceset → register existing object instanceInstanceFuncset → register from factory delegate- Add
Autofac.Moduleentries 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 = truewithTInterfaceset → register as explicit interface (As(interface))Interfaces = truewithoutTInterface→ register all implemented interfaces (AsImplementedInterfaces())Singleton = true→ singleton lifetime (Reuse.Singleton)Singleton = false→ transient lifetime (default)Instanceset → register existing object instance (RegisterInstanceMany)InstanceFuncset → register from factory delegate (RegisterDelegate)DryModuleentries → use DryIocContainer.RegisterMappingfor 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 onFinalize()Add(List<Action<IServiceCollection>>)→ Batch add registration actionsFinalize()→ Build theIServiceProviderfrom collected registrationsProvider→ Access the underlyingIServiceProvider
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:
- Feature Index
- Core Capabilities
- Migration Guide - Upgrading from older versions, breaking changes, and adapter migration paths
| Product | Versions 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. |
-
net10.0
- Autofac (>= 7.1.0)
- PolyhydraGames.Core.Interfaces (>= 3.0.0.14)
- PolyhydraGames.Core.IOC (>= 2.0.0.2)
-
net8.0
- Autofac (>= 7.1.0)
- PolyhydraGames.Core.Interfaces (>= 3.0.0.14)
- PolyhydraGames.Core.IOC (>= 2.0.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.