Home > database >  How to get Service instance using generic asp.net core
How to get Service instance using generic asp.net core

Time:06-23

I am working on a console application where I want to get the instance of a generic service type. Here is my implementation it gives me null.

 public class HelperService
        {
            private readonly ServiceCollection collection;
            private readonly IServiceProvider serviceProvider;
            public HelperService()
            {
                collection = new ServiceCollection();
                serviceProvider = collection.BuildServiceProvider();
            }
            public void RegisterService()
            {
                #region [register Services]
    
                collection.AddScoped<ICustomerService, CustomerService>();
    
                #endregion
    
            }
    
            public T? GetServiceInstance<T>() where T : class
            {
                return serviceProvider.GetService<T>()?? null;
            }
    
        }

var helperService = new HelperService();
helperService.RegisterService();
var result = helperService.GetServiceInstance<ICustomerService>(); // result is null

I want to implement generic service to which I will pass any service and it will give instance.

CodePudding user response:

You are adding service to collection after the IServiceProvider was build so it will not know anything about this newly added service, you need to add service before building the provider:

    public class HelperService
    {
        private readonly ServiceCollection collection;
        private readonly IServiceProvider serviceProvider;
        public HelperService()
        {
            collection = new ServiceCollection();
            #region [register Services]

            collection.AddScoped<ICustomerService, CustomerService>();

            #endregion
            serviceProvider = collection.BuildServiceProvider();
        }

        public T? GetServiceInstance<T>() where T : class
        {
            return serviceProvider.GetService<T>();
        }
    }

Also ?? null does not make much sense and can be removed.

And in general I would say that such wrapper is not very helpful, at least based on provided code.

  • Related