GithubHelp home page GithubHelp logo

patrickklaeren / autoregisterinject Goto Github PK

View Code? Open in Web Editor NEW
63.0 63.0 5.0 92 KB

C# Source Generator to automatically register dependencies in Microsoft Dependency Injection Service Collection

License: MIT License

C# 100.00%
csharp dependency-injection microsoft source-generator

autoregisterinject's Introduction

Hey there, the name's Patrick ๐Ÿ‘‹

Metrics

autoregisterinject's People

Contributors

chasedredmon avatar patrickklaeren avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

autoregisterinject's Issues

Generated Extension Methods contribute to build warnings

We've got a project with:

   <PropertyGroup>
      <GenerateDocumentationFile>true</GenerateDocumentationFile>
   </PropertyGroup>

We rely on warnings to help us find undocumented public methods. When using AutoRegisterInject, we get these build issues

...\AccountSvc\srcs\webs\WebApi\AutoRegisterInject\AutoRegisterInject.Generator\AutoRegisterInject.ServiceCollectionExtension.g.cs(7,21,7,65): warning CS1591: Missing XML comment for publicly visible type or member 'AutoRegisterInjectServiceCollectionExtension'
...\WebApi\AutoRegisterInject\AutoRegisterInject.Generator\AutoRegisterInject.ServiceCollectionExtension.g.cs(9,79,9,117): warning CS1591: Missing XML comment for publicly visible type or member 'AutoRegisterInjectServiceCollectionExtension.AutoRegisterFromAccountWebApi(IServiceCollection)'

I considered attempting to suppress the warnings by first seeing if I couldn't extended the generated code with partial implementations, but the generated code isn't partial.

// <auto-generated>
//     Automatically generated by AutoRegisterInject.
//     Changes made to this file may be lost and may cause undesirable behaviour.
// </auto-generated>
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
public static class AutoRegisterInjectServiceCollectionExtension
{
    public static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegisterFromTaylorUFPAccountWebApi(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        return AutoRegister(serviceCollection);
    }

    internal static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegister(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        
        return serviceCollection;
    }
}

The generated code could supply xml comments or suppress warnings related to them. I'm unsure which would be the better solution.

Support for Option Pattern

Hi everyone,

it would be cool if you could add support for the Options Pattern.

If there is at least one class that uses the attribute, the generated method should be: serviceCollection.AutoRegister(IConfiguration configuration);

An attribute might look like this:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class OptionAttribute : Attribute {
    public string? Section {get;}

    public OptionAttribute(string? section = null) {
        Section = section;
    }
}

Possible Usages:

[Option]
public record RootOption {}

[Option("SectionOption")]
public record SectionOption {}

[Option("SectionOption:InnerSection:MoreInnerSection")]
public record InnerSectionOption {}

Thank you

Doesn't register as abstract service, only as implementation.

I have this class:

public sealed class Settings
{
   public required string ConnectionString { get; init; }
}

I have a fluent validator like so:

[RegisterTransient(typeof(IValidator<Settings>))]
public class SettingsValidator : AbstractValidator<Settings>
{
   public SettingsValidator() =>
      RuleFor(static settings => settings.ConnectionString)
        .NotEmpty()
        .WithMessage($"{nameof(Settings.ConnectionString)} must have a valid connection string.")
        .Must(BeAbleToConnect)
        .WithMessage($"{nameof(Settings.ConnectionString)} is not valid or cannot connect to the database.");

   static bool BeAbleToConnect(string connectionString)
   {
      try
      {
         using SqlConnection connection = new (connectionString);

         connection.Open();

         return true;
      }
      catch { return false; }
   }
}

I expect it to register like so:

serviceCollection.AddSingleton<IValidator<Settings>, SettingsValidator>();

However, it always registers it like this instead:

// <auto-generated>
//     Automatically generated by AutoRegisterInject.
//     Changes made to this file may be lost and may cause undesirable behaviour.
// </auto-generated>
using Microsoft.Extensions.DependencyInjection;
public static class AutoRegisterInjectServiceCollectionExtension
{
    public static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegisterFromMyProject(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        return AutoRegister(serviceCollection);
    }

    internal static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegister(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        serviceCollection.AddTransient<MyProject.SettingsValidator>();
        return serviceCollection;
    }
}

Support Generated Interfaces

We are actually generating our interfaces (we're actually using multiple generators together).

[AutoInterface]
[AutoConstruct]
public partial class ItemsService : IItemsService
{
   // removed for brevity
}

However, AutoRegisterInject isn't finding our generated interfaces.

Both:

[AutoInterface]
[AutoConstruct]
[RegisterTransient]
public partial class ItemsService : IItemsService
{
   // removed for brevity
}

And:

[AutoInterface]
[AutoConstruct]
[RegisterTransient(typeof(IItemsService))]
public partial class ItemsService : IItemsService
{
   // removed for brevity
}

Produce:

// <auto-generated>
//     Automatically generated by AutoRegisterInject.
//     Changes made to this file may be lost and may cause undesirable behaviour.
// </auto-generated>
using Microsoft.Extensions.DependencyInjection;
public static class AutoRegisterInjectServiceCollectionExtension
{
    public static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegisterFromServices(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        return AutoRegister(serviceCollection);
    }

    internal static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegister(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        serviceCollection.AddTransient<Services.ItemsService>();
        return serviceCollection;
    }
}

Not sure whether it will be possible to address this due to the use of multiple generators. Was hoping to not have to chose one generator in favor of another when they do not compete in equivalent features.

Request Support for InternalsVisibleTo with Exclude Symbol

We have some assemblies that share internals with other assemblies. This is causing some warning and ambiguity issues:

'D:...Services\obj\Release\net8.0-windows\AutoRegisterInject\AutoRegisterInject.Generator\AutoRegisterInject.Attributes.g.cs' conflicts with the imported type 'TryRegisterTransientAttribute' in '....Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. 
Using the type defined in 'D:...Services\obj\Release\net8.0-windows\AutoRegisterInject\AutoRegisterInject.Generator\AutoRegisterInject.Attributes.g.cs'.

Other generator projects I've used will sometimes provide a symbol to control whether internals are generated or not.

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

   <PropertyGroup>
      <DefineConstants>$(DefineConstants);AUTOREGISTERINJECT_EXCLUDE_ATTRIBUTES</DefineConstants>
   </PropertyGroup>

</Project>
// <auto-generated>
//     Automatically generated by AutoRegisterInject.
//     Changes made to this file may be lost and may cause undesirable behaviour.
// </auto-generated>
#if !AUTOREGISTERINJECT_EXCLUDE_ATTRIBUTES
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterScopedAttribute : System.Attribute
{ 
    internal RegisterScopedAttribute(params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterKeyedScopedAttribute : System.Attribute
{ 
    internal RegisterKeyedScopedAttribute(string serviceKey, params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class TryRegisterScopedAttribute : System.Attribute
{ 
    internal TryRegisterScopedAttribute(params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class TryRegisterKeyedScopedAttribute : System.Attribute
{ 
    internal TryRegisterKeyedScopedAttribute(string serviceKey, params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterSingletonAttribute : System.Attribute
{ 
    internal RegisterSingletonAttribute(params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterKeyedSingletonAttribute : System.Attribute
{ 
    internal RegisterKeyedSingletonAttribute(string serviceKey, params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class TryRegisterSingletonAttribute : System.Attribute
{ 
    internal TryRegisterSingletonAttribute(params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class TryRegisterKeyedSingletonAttribute : System.Attribute
{ 
    internal TryRegisterKeyedSingletonAttribute(string serviceKey, params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterTransientAttribute : System.Attribute
{ 
    internal RegisterTransientAttribute(params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterKeyedTransientAttribute : System.Attribute
{ 
    internal RegisterKeyedTransientAttribute(string serviceKey, params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class TryRegisterTransientAttribute : System.Attribute
{ 
    internal TryRegisterTransientAttribute(params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class TryRegisterKeyedTransientAttribute : System.Attribute
{ 
    internal TryRegisterKeyedTransientAttribute(string serviceKey, params System.Type[] onlyRegisterAs) { }
}

[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterHostedServiceAttribute : System.Attribute { }
#endif

Here's the PR for my suggested changes

#15

Thanks,

Support TryAdd methods

Instead of using methods such as AddTransient and AddSingleton, can it use TryAddTransient and TryAddSingleton (including the other possible lifetimes)? Or possibly make it configurable?

Ambiguous Extension Methods can be generated.

We have some projects named as such, within the same solution (yes I understand it's not ideal, but it's an established naming practice outside my control with a purpose irrelevant to the issue).

Account.Web.Api
Account.WebApi

Both these projects are creating an extension method named AutoRegisterAccountWebApi, which is then being detected as ambiguous.

Keyed services

Hi is there any plans for adding support for keyed services?

vNext roadmap

Tracking issue for vNext

This list represents issues and ideas to be implemented in vNext. Below will not necessarily be released at the same time, but rather over a longer term.

  • Add ability to ignore interfaces
  • Add ability to auto register hosted services

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.