Skip to content
Reza Ghadimi edited this page Mar 12, 2025 · 4 revisions

AutoWire.DI Wiki

NuGet Version

Welcome to the AutoWire.DI Wiki! This guide provides comprehensive details on using the AutoWire.DI library in your .NET projects.

Table of Contents

  1. Quick Start Example
  2. Features
  3. Service Lifetimes
  4. Keyed Service Registration
  5. Managing Multiple Interfaces
  6. Generic Type Support
  7. Detailed Feature Usage
  8. Keyed AutoInject Example

Quick Start Example

Get started with AutoWire.DI by simply adding the package to your project and utilizing automatic dependency injection in a few straightforward steps:

  1. Install the package:

    dotnet add package AutoWire.DI
  2. Annotate your service class with [AutoInject]:

using AutoWire.DI.Attributes;

[AutoInject(ServiceLifetime.Singleton)]
public class MySingletonService
{
    // Service logic here
}
  1. Register services using RegisterAutoInjectableServices in your startup configuration:
using AutoWire.DI.Extensions;
using Microsoft.Extensions.DependencyInjection;

public void ConfigureServices(IServiceCollection services)
{
    services.RegisterAutoInjectableServices();
}
  1. Use your service as needed in your application:
public class MyController
{
    private readonly MySingletonService _service;

    public MyController(MySingletonService service)
    {
        _service = service;
    }
    
    // Controller logic here
}

Features

  • Automatic Service Registration: Easily register services with minimal configuration.
  • Flexible Lifetime Control: Specify how long services should live.
  • Key-Based Registration: Support multiple instances with distinct identifiers.
  • Explicit Service Type Management: Resolve ambiguity when multiple interfaces are present.
  • Generic Type Handling: Define services with generic parameters effectively.

Service Lifetimes

Specify how the DI container manages service lifetimes:

  • Singleton: A single instance is shared throughout the application's lifecycle.

    [AutoInject(ServiceLifetime.Singleton)]
    public class SingletonService {}
  • Scoped: A new instance is created per request/connection (default).

    [AutoInject]
    public class ScopedService {}
  • Transient: A new instance is created each time it is requested.

    [AutoInject(ServiceLifetime.Transient)]
    public class TransientService {}

Keyed Service Registration

Register services with a unique key for disambiguation or identification:

[AutoInject("databaseService", ServiceLifetime.Singleton)]
public class DatabaseService {}

Managing Multiple Interfaces

Prevent ambiguity by explicitly defining which interface to register:

public interface ILogging {}
public interface IDebugging {}

[AutoInject(serviceType: typeof(ILogging))]
public class LogService : ILogging, IDebugging {}

Generic Type Support

Enable flexible service definitions that can work with a variety of types:

public interface IRepository<T> {}

[AutoInject(ServiceLifetime.Scoped)]
public class Repository<T> : IRepository<T>
{
    // Repository implementation
}

Detailed Feature Usage

AutoWire.DI ensures that your dependency injection setup is both simplified and robust, accommodating complex structures and minimizing configuration overhead:

  • Ease of Use: The [AutoInject] attribute minimizes manual service setup in DI containers.
  • Robust Error Handling: Includes exceptions like DuplicateServiceRegistrationException and AmbiguousServiceTypeException for clear error diagnostics.
  • Highly Configurable: Offers extensive customizability to fit diverse architectural patterns and requirements.

Keyed AutoInject Example

The [KeyedAutoInject]attribute allows you to register services with a unique key derived from the class name or a specified key. This is particularly useful when you need to manage multiple implementations of the same service type or when disambiguation is required.

  1. Define a Service Class with KeyedAutoInject:

    using AutoWire.DI.Attributes;
    
    // Uses the class name as the key
    [KeyedAutoInject]
    public class UserService
    {
        public void Execute()
        {
            Console.WriteLine("UserService is executing!");
        }
    }
    
    // Specifies a custom key
    [AutoInject("adminServiceKey")]
    public class AdminService
    {
        public void PerformAdminActions()
        {
            Console.WriteLine("AdminService is performing admin actions!");
        }
    }
  2. Using the Services: These services can now be resolved and used in your application.

    public class MyController
    {
        private readonly UserService _userService;
        private readonly AdminService _adminService;
    
        public MyController(
            [FromKeyedServices(nameof(UserService))] UserService userService,
            [FromKeyedServices(nameof(AdminService))] AdminService adminService)
        {
            _userService = userService;
            _adminService = adminService;
        }
    
        public void ExecuteServices()
        {
            _userService.Execute();
            _adminService.PerformAdminActions();
        }
    }