Skip to content

distantcam/AutoCtor

Repository files navigation

AutoCtor

Build Status NuGet Status Nuget Downloads

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;
-    }
}

Contents

NuGet packages

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

Examples

Basic

[AutoConstruct]
public partial class Basic
{
    private readonly IService _service;
    private readonly IList<string> _list = new List<string>();
}

snippet source | anchor

What gets generated

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

partial class Basic
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	public Basic(global::IService service)
	{
		this._service = service;
	}
}

snippet source | anchor

Inherited

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

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

partial class Inherited
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	public Inherited(
		global::IAnotherService anotherService,
		global::IService service
	) : base(anotherService)
	{
		this._service = service;
	}
}

snippet source | anchor

Properties

// 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

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

partial class Properties
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	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.

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

    [AutoPostConstruct]
    private void Initialize()
    {
    }
}

snippet source | anchor

What gets generated

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

partial class PostConstruct
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	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.

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

    [AutoPostConstruct]
    private void Initialize(IInitializeService initialiseService)
    {
    }
}

snippet source | anchor

What gets generated

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

partial class PostConstructWithParameter
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	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.

[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<IService>();
    }
}

snippet source | anchor

What gets generated

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

partial class PostConstructWithOutParameter
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	public PostConstructWithOutParameter(
		global::IOtherService otherService,
		global::IServiceProvider services
	)
	{
		this._otherService = otherService;
		Initialize(services, out this._service);
	}
}

snippet source | anchor

Optional Parameters

[AutoConstruct]
public partial class PostConstructWithDefaultParameter
{
    [AutoPostConstruct]
    private void Initialize(Service? service = default)
    {
    }
}

snippet source | anchor

What gets generated

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

partial class PostConstructWithDefaultParameter
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	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.

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

[AutoConstruct(GuardSetting.Enabled)]
public partial class Guarded
{
    private readonly IService _service;
}

snippet source | anchor

What gets generated

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

partial class Guarded
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	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.

[AutoConstruct]
public partial class Keyed
{
    [AutoKeyedService("key")]
    private readonly IService _keyedService;
}

snippet source | anchor

What gets generated

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

partial class Keyed
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
	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 <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>
What gets generated

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

#if AUTOCTOR_EMBED_ATTRIBUTES
namespace AutoCtor
{
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	internal enum GuardSetting
	{
		Default,
		Disabled,
		Enabled
	}
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[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.CompilerGeneratedAttribute]
	[global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class AutoPostConstructAttribute : global::System.Attribute
	{
	}
	[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
	[global::System.AttributeUsage(global::System.AttributeTargets.Field | global::System.AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
	internal sealed class AutoConstructIgnoreAttribute : global::System.Attribute
	{
	}
}
#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.

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

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

</Project>

Back to Contents

Stats

Alt

About

A Roslyn source generator for creating constructors.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Contributors 5

Languages