Skip to content

Latest commit

 

History

History
314 lines (185 loc) · 9.71 KB

readme.source.md

File metadata and controls

314 lines (185 loc) · 9.71 KB

AutoCtor

NuGet Status Nuget Downloads Build Status GitHub last commit

AutoCtor is a Roslyn Source Generator that will automatically create a constructor for your class for use with constructor Dependency Injection.

+[AutoConstruct]
public partial class AService
{
    private readonly IDataContext _dataContext;
    private readonly IDataService _dataService;
    private readonly IExternalService _externalService;
    private readonly ICacheService _cacheService;
    private readonly ICacheProvider _cacheProvider;
    private readonly IUserService _userService;

-    public AService(
-        IDataContext dataContext,
-        IDataService dataService,
-        IExternalService externalService,
-        ICacheService cacheService,
-        ICacheProvider cacheProvider,
-        IUserService userService
-    )
-    {
-        _dataContext = dataContext;
-        _dataService = dataService;
-        _externalService = externalService;
-        _cacheService = cacheService;
-        _cacheProvider = cacheProvider;
-        _userService = userService;
-    }
}

toc

NuGet packages

https://nuget.org/packages/AutoCtor/

Code Fixes (new in 3.0)

Starting in version 3.0, a new diagnostic has been introduced: ACTR007 Use [AutoConstruct] instead of manual constructor. This will appear on constructors that can be automatically converted to use [AutoConstruct]. A code fix is also available to perform the conversion automatically.

In 3.1 another code fix was added: Add [AutoConstruct] to type. This will add [AutoConstruct] to a type with no constructor and relevant fields. This is useful when working on a new type.

Service Provider Source Generator (new in 4.0)

In version 4.0 you can now generate your own Service Provider that will work with the constructors generated by AutoCtor. See Service Provider

Examples

Basic

snippet: Basic

What gets generated

snippet: Basic.cs#Basic.g.verified.cs

Inherited

snippet: Inherited

What gets generated

snippet: Inherited.cs#Inherited.g.verified.cs

Properties

snippet: Properties

What gets generated

snippet: Properties.cs#Properties.g.verified.cs

Back to Contents

Post Constructor Initialization

You can mark a method to be called at the end of the constructor with the attribute [AutoPostConstruct]. This method must return void.

snippet: PostConstruct

What gets generated

snippet: PostConstruct.cs#PostConstruct.g.verified.cs

Extra Parameters

Post construct methods can also take parameters. The generated constructor will include these parameters.

snippet: PostConstructWithParameter

What gets generated

snippet: PostConstructWithParameter.cs#PostConstructWithParameter.g.verified.cs

out/ref Parameters

Parameters marked with out or ref are set back to any fields that match the same type. This can be used to set readonly fields with more complex logic.

snippet: PostConstructWithOutParameter

What gets generated

snippet: PostConstructWithOutParameter.cs#PostConstructWithOutParameter.g.verified.cs

Optional Parameters

snippet: PostConstructWithDefaultParameter

What gets generated

snippet: PostConstructWithDefaultParameter.cs#PostConstructWithDefaultParameter.g.verified.cs

Back to Contents

Argument Guards

Null guards for the arguments to the constructor can be added in 2 ways.

In your project you can add a AutoCtorGuards property.

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

  <PropertyGroup>
    <AutoCtorGuards>true</AutoCtorGuards>
  </PropertyGroup>

</Project>

OR

In each AutoConstruct attribute you can add a setting to enable/disable guards.

snippet: Guarded

What gets generated

snippet: Guarded.cs#Guarded.g.verified.cs

Back to Contents

Keyed Services

When using Microsoft.Extensions.DependencyInjection you can mark fields and properties with [AutoKeyedService] and it will be included in the constructor.

snippet: Keyed

What gets generated

snippet: Keyed.cs#Keyed.g.verified.cs

Back to Contents

Service Provider

snippet: ServiceProvider

What gets generated

snippet: ServiceProvider.cs#Container.ServiceProvider.g.verified.cs

Add [ServiceProvider] to a blank partial class and register services with [Singleton], [Transient] or [Scoped] attributes.

The service provider is fully generated at compile time so there is no runtime reflection.

Multiple registrations for the same service can be returned with IEnumerable<T>. When getting just one the last registration wins.

Scanning

As well as registering services individually there is also an option to scan for services. Scanning is performed at compile time.

snippet: ServiceProviderScan

What gets generated

snippet: ServiceProviderScan.cs#OrderContainer.ServiceProvider.g.verified.cs

The scan attributes [ScanSingleton], [ScanTransient], and [ScanScoped] have some options.

  • As determines what to register the service as: ScanAs.Service, the service being scanned for (default); ScanAs.Self, the type itself; ScanAs.ImplementedInterfaces, all the interfaces the type has.
  • FromAssembliesOf can be used to scan other assemblies instead of the one the provider is in; add the provider too to keep it in the list of assemblies to scan.
  • TypeNameFilter only includes types whose name matches, where * matches anything and ? any one character, e.g. "*Repository". The service can be left out to select by name alone.

Keyed Services

snippet: ServiceProviderKeyed

What gets generated

snippet: ServiceProviderKeyed.cs#PaymentContainer.ServiceProvider.g.verified.cs

Factories

snippet: ServiceProviderFactory

What gets generated

snippet: ServiceProviderFactory.cs#HostContainer.ServiceProvider.g.verified.cs

Falling back to another provider

Fallback on [ServiceProvider] names a member to use when there is no registration for that service.

snippet: ServiceProviderFallback

What gets generated

snippet: ServiceProviderFallback.cs#FallbackContainer.ServiceProvider.g.verified.cs

Modules

[Import<TModule>] (or [Import(typeof(TModule))]) adds all the registrations from another type. Modules just act as markers so no code is generated for them.

snippet: ServiceProviderModule

What gets generated

snippet: ServiceProviderModule.cs#TestContainer.ServiceProvider.g.verified.cs

A module can live in another assembly, but the registration attributes are [Conditional], so that assembly has to define AUTOCTOR_USAGES (see Keeping Attributes In Code) for them to be there to read.

Back to Contents

Other

Embedding The Attributes

By default, the [AutoConstruct] attributes referenced in your project are contained in an external dll. It is also possible to embed the attributes directly in your project. To do this, you must do two things:

  1. Define the constant AUTOCTOR_EMBED_ATTRIBUTES. This ensures the attributes are embedded in your project.
  2. Add compile to the list of excluded assets in your <PackageReference> element. This ensures the attributes in your project are referenced, instead of the AutoCtor.Attributes.dll library.

Your project file should look like this:

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

  <PropertyGroup>
    <!--  Define the MSBuild constant    -->
    <DefineConstants>$(DefineConstants);AUTOCTOR_EMBED_ATTRIBUTES</DefineConstants>
  </PropertyGroup>

  <!-- Add the package -->
  <PackageReference Include="AutoCtor"
                    PrivateAssets="all"
                    ExcludeAssets="compile;runtime" />
  <!--                             ☝ Add compile to the list of excluded assets. -->

</Project>

The generic forms of [Singleton], [Transient] and [Scoped] are a C# 11 feature, so they are not embedded by default. If your project targets C# 11 or later and you want them, also define AUTOCTOR_EMBED_GENERIC_ATTRIBUTES.

What gets generated

snippet: GeneratedAttributeTests.cs#AutoConstructAttribute.g.verified.cs

Keeping Attributes In Code

The [AutoConstruct] attributes are decorated with the [Conditional] attribute, so their usage will not appear in the build output of your project. If you use reflection at runtime you will not find the [AutoConstruct] attributes.

If you wish to preserve these attributes in the build output, add the define constant AUTOCTOR_USAGES.

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

  <PropertyGroup>
    <!--  Define the MSBuild constant    -->
    <DefineConstants>$(DefineConstants);AUTOCTOR_USAGES</DefineConstants>
  </PropertyGroup>

</Project>

Back to Contents