简体   繁体   中英

How to get Service instance using generic asp.net core

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.

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 ?? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM