AutoCtor is a Roslyn Source Generator that will automatically create a constructor for your class for use with constructor Dependency Injection.
https://nuget.org/packages/AutoCtor/
[AutoConstruct]
public partial class ExampleClass
{
private readonly ICustomService _customService;
}
partial class ExampleClass
{
public ExampleClass(ICustomService customService)
{
_customService = customService;
}
}
You can also initialize readonly fields, and AutoCtor will not include them in the constructor.
[AutoConstruct]
public partial class ClassWithInitializer
{
private readonly ICustomService _customService;
private readonly IList<string> _list = new List<string>();
}
partial class ClassWithInitializer
{
public ClassWithInitializer(ICustomService customService)
{
_customService = customService;
// no code to set _list
}
}
If there is a single base constructor with parameters, AutoCtor will include that base constructor in the constructor it creates.
public abstract class BaseClass
{
protected IAnotherService _anotherService;
public BaseClass(IAnotherService anotherService)
{
_anotherService = anotherService;
}
}
[AutoConstruct]
public partial class ClassWithBase : BaseClass
{
private readonly ICustomService _customService;
}
partial class ClassWithBase
{
public ClassWithBase(IAnotherService anotherService, ICustomService customService) : base(anotherService)
{
_customService = customService;
}
}
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 MSBuild constant
AUTOCTOR_EMBED_ATTRIBUTES
. This ensures the attributes are embedded in your project. - Add
compile
to the list of excluded assets in your<PackageReference>
element. This ensures the attributes in your project are referenced, insted of the AutoCtor.Attributes.dll library.
Your project file should look like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Define the MSBuild constant -->
<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 [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, you can define the AUTOCTOR_USAGES
MSBuild variable.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Define the MSBuild constant -->
<DefineConstants>AUTOCTOR_USAGES</DefineConstants>
</PropertyGroup>
<!-- Add the package -->
<PackageReference Include="AutoCtor" PrivateAssets="all" />
</Project>