简体   繁体   English

如何使用通用 asp.net 核心获取服务实例

[英]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.这是我的实现,它给了我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:您在构建IServiceProvider之后将服务添加到集合中,因此它不会知道有关此新添加服务的任何信息,您需要在构建提供程序之前添加服务:

    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 ?? null does not make much sense and can be removed. ?? null没有多大意义,可以删除。

And in general I would say that such wrapper is not very helpful, at least based on provided code.总的来说,我会说这样的包装器不是很有帮助,至少基于提供的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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