Skip to content

Latest commit

 

History

History
109 lines (85 loc) · 2.03 KB

Gen-AutoInject.md

File metadata and controls

109 lines (85 loc) · 2.03 KB

Usage

//C#11(NET7+) support generic attribute
[AutoInject<T>(ServiceLifetime.Scoped)]

[AutoInject]
[AutoInject(serviceLifetime: ServiceLifetime.Transient)]
[AutoInject(typeof(ITest2Service), ServiceLifetime.Scoped)]


//C#12(NET8+) support keyed service
[AutoInjectKeyed<ITest2Service>("test", ServiceLifetime.Transient)]

Your Service

public interface ITestService
{
    string Say(string message);
}

public interface ITest2Service
{
    string Say2(string message);
}

[AutoInject<TestService>]
[AutoInject<ITestService>(ServiceLifetime.Singleton)]
[AutoInject<ITest2Service>(ServiceLifetime.Scoped)]
public class TestService : ITestService, ITest2Service
{
    public string Say(string message)
    {
        return $"hello {message}";
    }

    public string Say2(string message)
    {
        return message;
    }
}
[AutoInject]
[AutoInject<ITest2Service>]
public class TestService2 : ITest2Service
{
    public string Say2(string message)
    {
        return message;
    }
}

support .net8 keyed service

//NET8.0+ 支持keyed
[AutoInjectKeyed<ITest2Service>("test2", ServiceLifetime.Transient)]
[AutoInjectKeyed<ITest2Service>(nameof(TestService2))]
public class TestService2 : ITest2Service
{
    public string Say2(string message)
    {
        return message;
    }
}

Enjoy

// <auto-generated />
#pragma warning disable
public static class ServiceCollectionExtension
{
    /// <summary>
    /// 自动注册标注的服务
    /// </summary>
    /// <param name = "services"></param>
    /// <returns></returns>
    public static IServiceCollection AddAutoInject(this IServiceCollection services)
    {
        services.AddScoped<TestService>();
        services.AddSingleton<ITestService, TestService>();
        services.AddScoped<ITest2Service, TestService2>();
        return services;
    }
}
#pragma warning restore

Then .AddAutoInject()

  • 服务将自动注册到DI容器中
// add auto inject
builder.Services.AddAutoInject();

Report Diagnostic Code