API Reference

Complete reference for all PyNurseInjector APIs, methods, and configurations.

Extension Methods

Extension methods for IServiceCollection to register services.

AddServicesFrom

Registers all services from a specified namespace.

Overloads

// Register from namespace with default options
IServiceCollection AddServicesFrom(
    this IServiceCollection services, 
    string @namespace, 
    ServiceLifetime lifetime = ServiceLifetime.Transient, 
    bool deep = false)

// Register with configuration options
IServiceCollection AddServicesFrom(
    this IServiceCollection services, 
    string @namespace, 
    ServiceLifetime lifetime, 
    Action<DotNurseInjectorOptions> options)

// Register with expression-based selection
IServiceCollection AddServicesFrom(
    this IServiceCollection services, 
    Func<Type, bool> predicate, 
    ServiceLifetime lifetime = ServiceLifetime.Transient)

// Register with options and expression
IServiceCollection AddServicesFrom(
    this IServiceCollection services, 
    Func<Type, bool> predicate, 
    ServiceLifetime lifetime, 
    Action<DotNurseInjectorOptions> options)

Parameters

Parameter Type Description
services IServiceCollection The service collection to add services to
@namespace string The namespace to scan for services
lifetime ServiceLifetime Default lifetime for registered services (default: Transient)
deep bool Whether to include sub-namespaces (default: false)
options Action<DotNurseInjectorOptions> Configuration options for registration
predicate Func<Type, bool> Expression to filter types for registration

Examples

// Basic usage
services.AddServicesFrom("MyApp.Services");

// With lifetime
services.AddServicesFrom("MyApp.Repositories", ServiceLifetime.Scoped);

// With deep scan
services.AddServicesFrom("MyApp", deep: true);

// With options
services.AddServicesFrom("MyApp.Services", ServiceLifetime.Scoped, opts =>
{
    opts.SelectInterface = interfaces => interfaces.FirstOrDefault();
    opts.ImplementationBase = typeof(BaseService);
});

// With expression
services.AddServicesFrom(
    type => type.Namespace?.StartsWith("MyApp.") ?? false && 
            type.Name.EndsWith("Service"),
    ServiceLifetime.Scoped);

AddServicesByAttributes

Registers only services marked with [RegisterAs] attribute.

// Register from all loaded assemblies
IServiceCollection AddServicesByAttributes(
    this IServiceCollection services)

// Register from specific assemblies
IServiceCollection AddServicesByAttributes(
    this IServiceCollection services, 
    params Assembly[] assemblies)

Examples

// Register all attributed services
services.AddServicesByAttributes();

// Register from specific assembly
services.AddServicesByAttributes(typeof(MyService).Assembly);

// Register from multiple assemblies
services.AddServicesByAttributes(
    typeof(MyService).Assembly,
    typeof(AnotherService).Assembly);

UseDotNurseInjector

Enables property injection support for the application.

// Extension method for IHostBuilder
IHostBuilder UseDotNurseInjector(this IHostBuilder hostBuilder)

Usage

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

// For console apps
Host.CreateDefaultBuilder(args)
    .UseDotNurseInjector()
    .ConfigureServices((context, services) =>
    {
        // Configure services
    })
    .Build()
    .Run();

Attributes

Attributes for controlling service registration behavior.

[RegisterAs]

Specifies the interface(s) a class should be registered as.

Constructor

public RegisterAsAttribute(Type serviceType, ServiceLifetime lifetime = ServiceLifetime.Transient)

Properties

Property Type Description
ServiceType Type The interface type to register as
Lifetime ServiceLifetime Service lifetime (default: Transient)

Usage

// Single interface
[RegisterAs(typeof(IUserService))]
public class UserService : IUserService { }

// With lifetime
[RegisterAs(typeof(ICacheService), ServiceLifetime.Singleton)]
public class CacheService : ICacheService { }

// Multiple interfaces
[RegisterAs(typeof(IEmailService))]
[RegisterAs(typeof(INotificationService), ServiceLifetime.Scoped)]
public class EmailService : IEmailService, INotificationService { }

[ServiceLifeTime]

Overrides the default service lifetime.

Constructor

public ServiceLifeTimeAttribute(ServiceLifetime lifetime)

Usage

[ServiceLifeTime(ServiceLifetime.Singleton)]
public class ConfigurationService : IConfigurationService { }

// Can be combined with RegisterAs
[RegisterAs(typeof(ILogger))]
[ServiceLifeTime(ServiceLifetime.Singleton)]
public class FileLogger : ILogger { }

[DontRegister]

Excludes a type from automatic registration.

Constructor

public DontRegisterAttribute()

Usage

[DontRegister]
public class InternalService : IService
{
    // Won't be registered even if in scanned namespace
}

[DontRegister]
internal class TestHelper : IHelper
{
    // Useful for test utilities
}

[InjectService]

Marks a property or field for dependency injection.

Constructor

public InjectServiceAttribute()

Usage

public class MyController : Controller
{
    // Property injection
    [InjectService] 
    public IMyService MyService { get; private set; }
    
    // Field injection
    [InjectService] 
    private readonly ILogger<MyController> logger;
    
    // Protected field
    [InjectService] 
    protected IRepository repository;
}

Note: Property/field injection requires calling UseDotNurseInjector() on the host builder.

Configuration Options

Options for customizing service registration behavior.

DotNurseInjectorOptions

Configuration options for service registration.

Properties

Property Type Description
SelectInterface Func<Type[], Type> Selects which interface to register when multiple exist
SelectImplementation Func<Type, bool> Filters which implementations to register
ImplementationBase Type Only register types inheriting from this base type
SelfRegister bool Also register the implementation type itself

Examples

services.AddServicesFrom("MyApp.Services", ServiceLifetime.Scoped, options =>
{
    // Select primary interface
    options.SelectInterface = interfaces => 
        interfaces.FirstOrDefault(i => i.Name.StartsWith("I"));
    
    // Filter implementations
    options.SelectImplementation = type => 
        !type.Name.Contains("Mock") && 
        !type.IsAbstract;
    
    // Base type filter
    options.ImplementationBase = typeof(BaseService);
    
    // Enable self-registration
    options.SelfRegister = true;
});

Core Interfaces

Core interfaces used internally by PyNurseInjector.

IDotNurseServiceProvider

Custom service provider that enables property injection.

public interface IDotNurseServiceProvider : IServiceProvider
{
    object GetService(Type serviceType);
}

ITypeExplorer

Interface for type discovery and exploration.

public interface ITypeExplorer
{
    IEnumerable<Type> GetTypes(string @namespace, bool deep = false);
    IEnumerable<Type> GetTypes(Func<Type, bool> predicate);
    IEnumerable<Type> GetTypesFromAssembly(Assembly assembly);
}

DotNurseServiceProvider

The custom service provider that enables property injection.

DotNurseServiceProvider

Wraps the default service provider to add property injection support.

Constructor

public DotNurseServiceProvider(IServiceProvider serviceProvider)

Methods

// Get service with property injection
public object GetService(Type serviceType)
{
    var service = _serviceProvider.GetService(serviceType);
    
    if (service != null)
    {
        InjectProperties(service);
    }
    
    return service;
}

// Inject properties marked with [InjectService]
private void InjectProperties(object instance)
{
    var type = instance.GetType();
    
    // Inject into properties
    var properties = type.GetProperties(BindingFlags.Public | 
                                       BindingFlags.NonPublic | 
                                       BindingFlags.Instance)
        .Where(p => p.GetCustomAttribute<InjectServiceAttribute>() != null);
    
    foreach (var property in properties)
    {
        var service = GetService(property.PropertyType);
        property.SetValue(instance, service);
    }
    
    // Inject into fields
    var fields = type.GetFields(BindingFlags.Public | 
                               BindingFlags.NonPublic | 
                               BindingFlags.Instance)
        .Where(f => f.GetCustomAttribute<InjectServiceAttribute>() != null);
    
    foreach (var field in fields)
    {
        var service = GetService(field.FieldType);
        field.SetValue(instance, service);
    }
}

DotNurseTypeExplorer

Handles type discovery and filtering for service registration.

DotNurseTypeExplorer

Explores assemblies to find types for registration.

Methods

// Get types from namespace
public IEnumerable<Type> GetTypes(string @namespace, bool deep = false)
{
    var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    var types = new List<Type>();
    
    foreach (var assembly in assemblies)
    {
        types.AddRange(assembly.GetTypes()
            .Where(t => IsInNamespace(t, @namespace, deep)));
    }
    
    return types;
}

// Get types matching predicate
public IEnumerable<Type> GetTypes(Func<Type, bool> predicate)
{
    var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    var types = new List<Type>();
    
    foreach (var assembly in assemblies)
    {
        types.AddRange(assembly.GetTypes().Where(predicate));
    }
    
    return types;
}

// Check if type is in namespace
private bool IsInNamespace(Type type, string @namespace, bool deep)
{
    if (type.Namespace == null) return false;
    
    if (deep)
    {
        return type.Namespace.StartsWith(@namespace);
    }
    
    return type.Namespace == @namespace;
}

Quick Reference

Registration Methods

  • AddServicesFrom(namespace) - Register from namespace
  • AddServicesFrom(predicate) - Register with expression
  • AddServicesByAttributes() - Register attributed services
  • UseDotNurseInjector() - Enable property injection

Attributes

  • [RegisterAs(type)] - Specify registration interface
  • [ServiceLifeTime(lifetime)] - Override lifetime
  • [DontRegister] - Exclude from registration
  • [InjectService] - Mark for property injection

Service Lifetimes

  • ServiceLifetime.Transient - New instance each time
  • ServiceLifetime.Scoped - One instance per scope
  • ServiceLifetime.Singleton - Single instance