Skip to content

Source generator for boilerplate code such as registering and injecting services

License

Notifications You must be signed in to change notification settings

Chacaroon/AutoDependencies

Repository files navigation

AutoDependencies

BuildAndPublish NuGet

AutoDependencies is a library designed to get rid of boilerplate code in ASP.NET services by generating it with Incremental Generator.

Features

  • Generate a partial service
  • Generate constructor with injected services and save ones to the appropriate service members
  • Generate an interface with public methods of a service
  • Generate code with Incremental Generator
  • Create and publish nuget packages
  • Cover generator with tests
  • Generate method that registers all generated services to the IServiceCollection
  • Support for a custom constructor in addition to the generated one
  • Add code analyzer with code fix
  • Generate an interface for the service depending on a flag (i.e. supress interface generation)

Installation

Add the package to your application using

Install-Package AutoDependencies.Generator

This adds a <PackageReference> to your project. You can additionally mark the package as PrivateAssets="all".

Setting PrivateAssets="all" means any projects referencing this one won't get a reference to the AutoDependencies.Generator package.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <!-- Add the package -->
  <PackageReference Include="AutoDependencies.Generator" Version="..." PrivateAssets="all"/>

</Project>

Adding the package will automatically add a marker attributes, such as [Service] and [Inject], to your project.

Usage

First, create the service with some dependencies and public methods. Mark just created service with [Service] attribute, so source generator will process it.

using AutoDependencies.Attributes;

namespace Services;

[Service]
partial class SampleService
{
    private readonly IDependency _dependency;

    public void DoWork() 
    {
        _dependency.DoAnotherWork();
    }
}

Once you do this, the incremental generator will generate:

  • an interface based on public methods of the service;
  • a constructor that injects and initializes dependencies based on private readonly properties;
  • extension method for IServiceCollection that registers the generated services;

What's next

Check out more detailed guides on the various features:
🛠️ Service generation 🛠️
📜 Interface generation 📜
🔗 Injecting dependencies 🔗
🧰 Custom constructor 🧰
💥 Service collection extension 💥