Generate primary constructor from readonly fields & properties
PM> Install-Package PrimaryConstructor
Visual Studio version 16.8 and above is required as its first version to support source generators.
Declare class with partial
, and annotate with [PrimaryConstructor]
.
And then you can declare your dependencies with readonly fields.
[PrimaryConstructor]
public partial class MyService
{
private readonly MyDependency _myDependency;
...
}
When compile, following source will be injected.
partial class MyService
{
public MyService(MyDependency myDependency)
{
this._myDependency = myDependency;
}
}
- readonly fields & properties without initializer will be automatically injected.
- if the service has based type, based type must also annotated with
PrimaryConstructor
in order to inject members from based type. - you can exclude members from injection by annotated with
IgnorePrimaryConstructor
. - you can include members to injection by annotated with
IncludePrimaryConstructor
.
Visual Studio still not fully support source generator, it sometimes shows error marker on symbols referred to the generated code. Emitting the generated files will allow you to see the code, and also solve Visual Studio error marker problem.
To emit generated files, add following code to your csproj
file.
<PropertyGroup>
<CompilerGeneratedFilesOutputPath>$(MSBuildProjectDirectory)/generated</CompilerGeneratedFilesOutputPath>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
<Target Name="ExcludeGenerated" BeforeTargets="AssignTargetPaths">
<ItemGroup>
<Generated Include="generated/**/*.g.cs" />
<Compile Remove="@(Generated)" />
</ItemGroup>
<Delete Files="@(Generated)" />
</Target>
Please check PrimaryConstructor.Sample.csproj for sample.