An open API service indexing awesome lists of open source software.

https://github.com/distantcam/autoctor

A Roslyn source generator for creating constructors.
https://github.com/distantcam/autoctor

csharp csharp-sourcegenerator dotnet roslyn source-generator

Last synced: 5 days ago
JSON representation

A Roslyn source generator for creating constructors.

Awesome Lists containing this project

README

          

# AutoCtor

[![Build Status](https://img.shields.io/github/actions/workflow/status/distantcam/autoctor/build.yml)](https://github.com/distantcam/AutoCtor/actions/workflows/build.yml)
[![NuGet Status](https://img.shields.io/nuget/v/AutoCtor.svg)](https://www.nuget.org/packages/AutoCtor/)
[![Nuget Downloads](https://img.shields.io/nuget/dt/autoctor.svg)](https://www.nuget.org/packages/AutoCtor/)

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

```diff
+[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;
- }
}
```

## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=distantcam/autoctor&type=date&legend=top-left)](https://www.star-history.com/#distantcam/autoctor&type=date&legend=top-left)

## Contents

* [NuGet packages](#nuget-packages)
* [Examples](#examples)
* [Basic](#basic)
* [Inherited](#inherited)
* [Properties](#properties)
* [Post Constructor Initialization](#post-constructor-initialization)
* [Extra Parameters](#extra-parameters)
* [`out`/`ref` Parameters](#outref-parameters)
* [Optional Parameters](#optional-parameters)
* [Argument Guards](#argument-guards)
* [Keyed Services](#keyed-services)
* [Other](#other)
* [Embedding The Attributes](#embedding-the-attributes)
* [Keeping Attributes In Code](#keeping-attributes-in-code)
* [Stats](#stats)

## NuGet packages

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

## Examples

### Basic


```cs
[AutoConstruct]
public partial class Basic
{
private readonly IService _service;
private readonly IList _list = new List();
}
```
snippet source | anchor

What gets generated


```cs
//HintName: Basic.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class Basic
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Basic(global::IService service)
{
this._service = service;
}
}
```
snippet source | anchor

### Inherited


```cs
public abstract class BaseClass
{
protected IAnotherService _anotherService;

public BaseClass(IAnotherService anotherService)
{
_anotherService = anotherService;
}
}

[AutoConstruct]
public partial class Inherited : BaseClass
{
private readonly IService _service;
}
```
snippet source | anchor

What gets generated


```cs
//HintName: Inherited.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class Inherited
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Inherited(
global::IAnotherService anotherService,
global::IService service
) : base(anotherService)
{
this._service = service;
}
}
```
snippet source | anchor

### Properties


```cs
// AutoCtor will initialize these
public string GetProperty { get; }
protected string ProtectedProperty { get; }
public string InitProperty { get; init; }
public required string RequiredProperty { get; set; }

// AutoCtor will ignore these
public string InitializerProperty { get; } = "Constant";
public string GetSetProperty { get; set; }
public string FixedProperty => "Constant";
public string RedirectedProperty => InitializerProperty;
```
snippet source | anchor

What gets generated


```cs
//HintName: Properties.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class Properties
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Properties(
string getProperty,
string protectedProperty,
string initProperty,
string requiredProperty
)
{
this.GetProperty = getProperty;
this.ProtectedProperty = protectedProperty;
this.InitProperty = initProperty;
this.RequiredProperty = requiredProperty;
}
}
```
snippet source | anchor

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.


```cs
[AutoConstruct]
public partial class PostConstruct
{
private readonly IService _service;

[AutoPostConstruct]
private void Initialize()
{
}
}
```
snippet source | anchor

What gets generated


```cs
//HintName: PostConstruct.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class PostConstruct
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public PostConstruct(global::IService service)
{
this._service = service;
Initialize();
}
}
```
snippet source | anchor

### Extra Parameters

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


```cs
[AutoConstruct]
public partial class PostConstructWithParameter
{
private readonly IService _service;

[AutoPostConstruct]
private void Initialize(IInitializeService initialiseService)
{
}
}
```
snippet source | anchor

What gets generated


```cs
//HintName: PostConstructWithParameter.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class PostConstructWithParameter
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public PostConstructWithParameter(
global::IService service,
global::IInitializeService initialiseService
)
{
this._service = service;
Initialize(initialiseService);
}
}
```
snippet source | anchor

### `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.


```cs
[AutoConstruct]
public partial class PostConstructWithOutParameter
{
private readonly IService _service;
private readonly IOtherService _otherService;

[AutoPostConstruct]
private void Initialize(IServiceProvider services, out IService service)
{
service = services.GetService();
}
}
```
snippet source | anchor

What gets generated


```cs
//HintName: PostConstructWithOutParameter.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class PostConstructWithOutParameter
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public PostConstructWithOutParameter(
global::IOtherService otherService,
global::IServiceProvider services
)
{
this._otherService = otherService;
Initialize(services, out this._service);
}
}
```
snippet source | anchor

### Optional Parameters


```cs
[AutoConstruct]
public partial class PostConstructWithDefaultParameter
{
[AutoPostConstruct]
private void Initialize(Service? service = default)
{
}
}
```
snippet source | anchor

What gets generated


```cs
//HintName: PostConstructWithDefaultParameter.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class PostConstructWithDefaultParameter
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public PostConstructWithDefaultParameter(global::Service service = default)
{
Initialize(service);
}
}
```
snippet source | anchor

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.

```xml


true

```

**OR**

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


```cs
[AutoConstruct(GuardSetting.Enabled)]
public partial class Guarded
{
private readonly IService _service;
}
```
snippet source | anchor

What gets generated


```cs
//HintName: Guarded.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class Guarded
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Guarded(global::IService service)
{
this._service = service ?? throw new global::System.ArgumentNullException("service");
}
}
```
snippet source | anchor

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.


```cs
[AutoConstruct]
public partial class Keyed
{
[AutoKeyedService("key")]
private readonly IService _keyedService;
}
```
snippet source | anchor

What gets generated


```cs
//HintName: Keyed.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

partial class Keyed
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Keyed(
[global::Microsoft.Extensions.DependencyInjection.FromKeyedServices("key")] global::IService keyedService
)
{
this._keyedService = keyedService;
}
}
```
snippet source | anchor

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 `` element. This ensures the attributes in your project are referenced, instead of the _AutoCtor.Attributes.dll_ library.

Your project file should look like this:

```xml



$(DefineConstants);AUTOCTOR_EMBED_ATTRIBUTES



```

What gets generated


```cs
//HintName: AutoConstructAttribute.g.cs
//------------------------------------------------------------------------------
//
// This code was generated by https://github.com/distantcam/AutoCtor
//
//------------------------------------------------------------------------------

#if AUTOCTOR_EMBED_ATTRIBUTES
namespace AutoCtor
{
[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.CodeDom.Compiler.GeneratedCode("AutoCtor", "0.0.0.0")]
internal enum GuardSetting
{
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)]
internal sealed class AutoConstructAttribute : global::System.Attribute
{
public AutoConstructAttribute(GuardSetting guard = 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)]
internal sealed class AutoPostConstructAttribute : 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)]
internal sealed class AutoConstructIgnoreAttribute : 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)]
internal sealed class AutoKeyedServiceAttribute : global::System.Attribute
{
public object Key { get; }
public AutoKeyedServiceAttribute(object key) => Key = key;
}
}
#endif
```
snippet source | anchor

### 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`.

```xml



$(DefineConstants);AUTOCTOR_USAGES

```

Back to Contents
## Stats

![Alt](https://repobeats.axiom.co/api/embed/8d02b2c004a5f958b4365abad3d4d1882dca200f.svg "Repobeats analytics image")