Skip to content

依赖注入容器中注册工厂

扩展方法 AddFactory

// Source - https://stackoverflow.com/a/57430389
// Posted by Martin Brandl
// Retrieved 2025-12-01, License - CC BY-SA 4.0

public static class IServiceCollectionExtension
{
    public static IServiceCollection AddFactory<TService, TServiceImplementation>(this IServiceCollection serviceCollection) 
        where TService : class
        where TServiceImplementation : class, TService
    {
        return serviceCollection
            // 注册需要通过工厂被初始化的服务
            .AddTransient<TService, TServiceImplementation>()
            // 注册工厂函数
            .AddSingleton<Func<TService>>(sp => sp.GetRequiredService<TService>);
    }
}

手动工厂

假设需要传入参数到工厂函数中:

sc.AddSingleton<Func<string, IInterface>>(sp =>
{
    return parameter =>
    {
        var logger = sp.GetRequiredService<ILogger<Implementation>>();
        IInterface impl = new Implementation(parameter, logger);

        return impl;
    };
});

注入:

ctor(Func<string, IInterface> factory) { /*...*/ }

注意仅这个 Func 委托是单例的,实际上每次调用 factory() 时,都返回新的实例,生命周期上是 transient 的。

如果需要一个“单例工厂”的话,那直接 AddSingleton 就可以了,单例的依赖也一定是单例的(即使是被提升的)

Ref