Giter VIP home page Giter VIP logo

injectio-keyed-service's Introduction

Injectio

Source generator that helps register attribute marked services in the dependency injection ServiceCollection

Source generator

Features

  • Transient, Singleton, Scoped service registration
  • Factory registration
  • Module method registration
  • Duplicate Strategy - Skip,Replace,Append
  • Registration Strategy - Self, Implemented Interfaces, Self With Interfaces

Usage

Add package

Add the nuget package project to your projects.

dotnet add package Injectio

Prevent dependances from including Injectio

<PackageReference Include="Injectio" PrivateAssets="all" />

Registration Attributes

Place registration attribute on class. The class will be discovered and registered.

  • [RegisterSingleton] Marks the class as a singleton service
  • [RegisterScoped] Marks the class as a scoped service
  • [RegisterTransient] Marks the class as a transient service
  • [RegisterServices] Marks the method to be called to register services

Attribute Properties

Property Description
ImplementationType The type that implements the service. If not set, the class the attribute is on will be used.
ServiceType The type of the service. If not set, the Registration property used to determine what is registered.
Factory Name of a factory method to create new instances of the service implementation.
Duplicate How the generator handles duplicate registrations. See Duplicate Strategy
Registration How the generator determines what to register. See Registration Strategy

Duplicate Strategy

Value Description
Skip Skips registrations for services that already exists
Replace Replaces existing service registrations
Append Appends a new registration for existing services

Registration Strategy

Value Description
Self Registers each matching concrete type as itself
ImplementedInterfaces Registers each matching concrete type as all of its implemented interfaces
SelfWithInterfaces Registers each matching concrete type as all of its implemented interfaces and itself

Singleton services

[RegisterSingleton]
public class SingletonService : IService { }

Explicit service type

[RegisterSingleton(ServiceType = typeof(IService))]
public class SingletonService : IService { }

Support resolving multiple services with IEnumerable<T>

[RegisterSingleton(Duplicate = DuplicateStrategy.Append)]
public class SingletonService : IService { }

Scoped Services

[RegisterScoped]
public class ScopedService : IService { }

Transient Services

[RegisterTransient]
public class TransientService : IService { }

Factories

[RegisterTransient(Factory = nameof(ServiceFactory))]
public class FactoryService : IFactoryService
{
    private readonly IService _service;

    public FactoryService(IService service)
    { 
        _service = service;
    }

    public static IFactoryService ServiceFactory(IServiceProvider serviceProvider)
    {
        return new FactoryService(serviceProvider.GetService<IService>());
    }
}

Generic Attributes

You can use generic attributes to register services if your project targets net7.0.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net7.0</TargetFrameworks>
  </PropertyGroup>
</Project>

Generic attributes allow declaration to be more compact by avoiding the typeof calls

[RegisterSingleton<IService>]
public class ServiceImplementation : IService { }

Open Generic

[RegisterSingleton(ImplementationType = typeof(OpenGeneric<>), ServiceType = typeof(IOpenGeneric<>))]
public class OpenGeneric<T> : IOpenGeneric<T> { }

Register Method

When the service registration is complex, use the RegisterServices attribute on a method that has a parameter of IServiceCollection or ServiceCollection

public class RegistrationModule
{
    [RegisterServices]
    public static void Register(IServiceCollection services)
    {
        // add configuration options
        services
            .AddOptions<PollingOption>()
            .Configure<IConfiguration>((settings, configuration) => configuration
                .GetSection(PollingOption.SectionName)
                .Bind(settings)
            );
    }
}

Add to container

The source generator creates an extension method with all the discovered services registered. Call the generated extension method to add the services to the container. The extension method will be called Add[AssemblyName]. The assembly name will have the dots removed.

var services = new ServiceCollection();
services.AddInjectioTestsConsole();

Override the extension method name by using the InjectioName MSBuild property.

<PropertyGroup>
  <InjectioName>Library</InjectioName>
</PropertyGroup>
var services = new ServiceCollection();
services.AddLibrary();

Registration Tags

Control what is registered when calling the generated extension method using Tags

Tag the service

public interface IServiceTag
{
}

[RegisterSingleton(Tags = "Client,FrontEnd")]
public class ServiceTag : IServiceTag
{
}

Tags can be passed to register methods

public static class ServiceRegistration
{
    [RegisterServices]
    public static void Register(IServiceCollection services, ISet<string> tags)
    {

    }
}

Specify tags when adding to service collection. Note, if no tags specified, all services are registered

var services = new ServiceCollection();
services.AddInjectioTestsLibrary("Client");

injectio-keyed-service's People

Contributors

pwelter34 avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.