Skip to content

Factories and Keyed Services

Alexander Stärk edited this page Sep 25, 2026 · 1 revision

Factories and Keyed Services

Factory-based registration

Use Factory to create instances through a static factory method.

public static class MyServiceFactory
{
    public static MyService Create(IServiceProvider provider)
    {
        return new MyService();
    }
}

[RegisterServiceSingleton(Factory = typeof(MyServiceFactory))]
public class MyService { }

If the factory type has multiple candidate methods, set FactoryMethodName:

[RegisterServiceSingleton(
    Factory = typeof(MyServiceFactory),
    FactoryMethodName = "Create")]
public class MyService { }

Keyed services

Use Key to generate keyed registrations:

[RegisterServiceScoped(Key = "primary")]
public class PrimaryHandler : IHandler { }

[RegisterServiceScoped(Key = "secondary")]
public class SecondaryHandler : IHandler { }

Basilisque DI passes keyed metadata to the corresponding keyed registration APIs.

Keyed + factory

Keyed and factory registrations can be combined.

For keyed factory registrations, ensure the factory method signature matches keyed requirements.

Validation and diagnostics

The generator validates factory method signatures and reports diagnostics if:

  • no matching factory method can be determined
  • multiple ambiguous factory methods exist
  • the provided FactoryMethodName does not match a valid method

See Diagnostics and Troubleshooting.

Clone this wiki locally