How to use Func in built-in dependency injection

前端 未结 6 694
梦毁少年i
梦毁少年i 2021-02-14 11:17

Using asp.net 5 I\'d like my controller to be injected with a Funcinstead of T

For example:



        
6条回答
  •  一生所求
    2021-02-14 11:46

    I wrote a little extension method that registres the service and the factory (Func):

    public static class IServiceCollectionExtension
    {
        public static IServiceCollection AddFactory(this IServiceCollection serviceCollection) 
            where TService : class
            where TServiceImplementation : class, TService
        {
            return serviceCollection
                .AddTransient();
                .AddSingleton>(sp => sp.GetRequiredService);
        }
    }
    

    Usage:

    serviceCollection
       .AddFactory()
    

提交回复
热议问题