vipwan / Biwen.AutoClassGen

Source Gen Roslyn
MIT License
12 stars 0 forks source link

Support Auto Inject #7

Open vipwan opened 5 months ago

vipwan commented 5 months ago

提供自动注入的支持 .NET7+

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

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

    [AutoInject]
    [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;
        }
    }
vipwan commented 3 months ago

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

将会创建类似的代码:

public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddAutoInject(this Microsoft.Extensions.DependencyInjection.IServiceCollection services)
{
    services.AddKeyedTransient<Biwen.AutoClassGen.TestConsole.Services.ITest2Service, Biwen.AutoClassGen.TestConsole.Services.TestService2>("test2");
    services.AddKeyedScoped<Biwen.AutoClassGen.TestConsole.Services.ITest2Service, Biwen.AutoClassGen.TestConsole.Services.TestService2>("TestService2");
    return services;
}