Net Core Dependency Injection for Non-Controller

后端 未结 4 541
挽巷
挽巷 2020-12-05 07:40

Seems crazy that something like this is causing me such a headache. But here it is:

How do you use the built-in dependency injection for net core for a non-controll

4条回答
  •  有刺的猬
    2020-12-05 08:21

    You can easily define a static class with one property like:

    public static class StaticServiceProvider
    {
        public static IServiceProvider Provider { get; set; }    
    }
    

    after defined class you have to scope the service in the Startup.ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        //TODO: ...
    
        services.AddScoped();            
        services.AddSingleton();
    }
    
    

    then inside the Startup.Configure method on startup you can set the provider as static class property:

    public void Configure(IApplicationBuilder app, ...)
    {
        StaticServiceProvider.Provider = app.ApplicationServices;
    
        //TODO: ...
    }
    
    

    Now you can easily call StaticServiceProvider.Provider.GetService method almost everywhere in your application:

    var unitOfWork = (IUnitOfWork)StaticServiceProvider.Provider.GetService(typeof(IUnitOfWork));
    
    

提交回复
热议问题