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;- }
}- NuGet packages
- Code Fixes (new in 3.0)
- Examples
- Post Constructor Initialization
- Argument Guards
- Keyed Services
- Other
- Star History
- Stats
https://nuget.org/packages/AutoCtor/
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.
[AutoConstruct]publicpartialclassBasic{privatereadonlyIService_service;privatereadonlyIList<string>_list=newList<string>();}What gets generated
//HintName: Basic.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassBasic{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicBasic(global::IServiceservice){this._service=service;}}publicabstractclassBaseClass{protectedIAnotherService_anotherService;publicBaseClass(IAnotherServiceanotherService){_anotherService=anotherService;}}[AutoConstruct]publicpartialclassInherited:BaseClass{privatereadonlyIService_service;}What gets generated
//HintName: Inherited.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassInherited{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicInherited(global::IAnotherServiceanotherService,global::IServiceservice):base(anotherService){this._service=service;}}// AutoCtor will initialize thesepublicstringGetProperty{get;}protectedstringProtectedProperty{get;}publicstringInitProperty{get;init;}publicrequiredstringRequiredProperty{get;set;}// AutoCtor will ignore thesepublicstringInitializerProperty{get;}="Constant";publicstringGetSetProperty{get;set;}publicstringFixedProperty=> "Constant";publicstringRedirectedProperty=> InitializerProperty;What gets generated
//HintName: Properties.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassProperties{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicProperties(stringgetProperty,stringprotectedProperty,stringinitProperty,stringrequiredProperty){this.GetProperty=getProperty;this.ProtectedProperty=protectedProperty;this.InitProperty=initProperty;this.RequiredProperty=requiredProperty;}}You can mark a method to be called at the end of the constructor with the attribute [AutoPostConstruct]. This method must return void.
[AutoConstruct]publicpartialclassPostConstruct{privatereadonlyIService_service;[AutoPostConstruct]privatevoidInitialize(){}}What gets generated
//HintName: PostConstruct.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassPostConstruct{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicPostConstruct(global::IServiceservice){this._service=service;Initialize();}}Post construct methods can also take parameters. The generated constructor will include these parameters.
[AutoConstruct]publicpartialclassPostConstructWithParameter{privatereadonlyIService_service;[AutoPostConstruct]privatevoidInitialize(IInitializeServiceinitialiseService){}}What gets generated
//HintName: PostConstructWithParameter.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassPostConstructWithParameter{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicPostConstructWithParameter(global::IServiceservice,global::IInitializeServiceinitialiseService){this._service=service;Initialize(initialiseService);}}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.
[AutoConstruct]publicpartialclassPostConstructWithOutParameter{privatereadonlyIService_service;privatereadonlyIOtherService_otherService;[AutoPostConstruct]privatevoidInitialize(IServiceProviderservices,outIServiceservice){service=services.GetService<IService>();}}What gets generated
//HintName: PostConstructWithOutParameter.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassPostConstructWithOutParameter{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicPostConstructWithOutParameter(global::IOtherServiceotherService,global::IServiceProviderservices){this._otherService=otherService;Initialize(services,outthis._service);}}[AutoConstruct]publicpartialclassPostConstructWithDefaultParameter{[AutoPostConstruct]privatevoidInitialize(Service?service=default){}}What gets generated
//HintName: PostConstructWithDefaultParameter.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassPostConstructWithDefaultParameter{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicPostConstructWithDefaultParameter(global::Serviceservice=default){Initialize(service);}}Null guards for the arguments to the constructor can be added in 2 ways.
In your project you can add a AutoCtorGuards property.
<ProjectSdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AutoCtorGuards>true</AutoCtorGuards>
</PropertyGroup>
</Project>OR
In each AutoConstruct attribute you can add a setting to enable/disable guards.
[AutoConstruct(GuardSetting.Enabled)]publicpartialclassGuarded{privatereadonlyIService_service;}What gets generated
//HintName: Guarded.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassGuarded{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicGuarded(global::IServiceservice){this._service=service??thrownewglobal::System.ArgumentNullException("service");}}When using Microsoft.Extensions.DependencyInjection you can mark fields and properties with [AutoKeyedService] and it will be included in the constructor.
[AutoConstruct]publicpartialclassKeyed{[AutoKeyedService("key")]privatereadonlyIService_keyedService;}What gets generated
//HintName: Keyed.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------partialclassKeyed{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]publicKeyed([global::Microsoft.Extensions.DependencyInjection.FromKeyedServices("key")]global::IServicekeyedService){this._keyedService=keyedService;}}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:
- Define the constant
AUTOCTOR_EMBED_ATTRIBUTES. This ensures the attributes are embedded in your project. - Add
compileto 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:
<ProjectSdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Define the MSBuild constant -->
<DefineConstants>$(DefineConstants);AUTOCTOR_EMBED_ATTRIBUTES</DefineConstants>
</PropertyGroup>
<!-- Add the package -->
<PackageReferenceInclude="AutoCtor"PrivateAssets="all"ExcludeAssets="compile;runtime" />
<!-- ☝ Add compile to the list of excluded assets. -->
</Project>What gets generated
//HintName: AutoConstructAttribute.g.cs//------------------------------------------------------------------------------// <auto-generated>// This code was generated by https://github.com/distantcam/AutoCtor// </auto-generated>//------------------------------------------------------------------------------
#if AUTOCTOR_EMBED_ATTRIBUTESnamespaceAutoCtor{[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")]internalenumGuardSetting{Default,Disabled,Enabled}[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage][global::System.AttributeUsage(global::System.AttributeTargets.Class|global::System.AttributeTargets.Struct,AllowMultiple=false,Inherited=false)]internalsealedclassAutoConstructAttribute:global::System.Attribute{publicAutoConstructAttribute(GuardSettingguard=GuardSetting.Default){}}[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage][global::System.AttributeUsage(global::System.AttributeTargets.Method,AllowMultiple=false,Inherited=false)]internalsealedclassAutoPostConstructAttribute:global::System.Attribute{}[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage][global::System.AttributeUsage(global::System.AttributeTargets.Field|global::System.AttributeTargets.Property,AllowMultiple=false,Inherited=false)]internalsealedclassAutoConstructIgnoreAttribute:global::System.Attribute{}[global::System.Runtime.CompilerServices.CompilerGenerated][global::System.CodeDom.Compiler.GeneratedCode("AutoCtor","0.0.0.0")][global::System.Diagnostics.DebuggerNonUserCode][global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage][global::System.AttributeUsage(global::System.AttributeTargets.Field|global::System.AttributeTargets.Property|global::System.AttributeTargets.Parameter,AllowMultiple=false,Inherited=false)]internalsealedclassAutoKeyedServiceAttribute:global::System.Attribute{publicobjectKey{get;}publicAutoKeyedServiceAttribute(objectkey)=>Key=key;}}
#endifThe [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.
<ProjectSdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Define the MSBuild constant -->
<DefineConstants>$(DefineConstants);AUTOCTOR_USAGES</DefineConstants>
</PropertyGroup>
</Project>