.net core resolve dependency manually anywhere in the code

前端 未结 1 1416
旧时难觅i
旧时难觅i 2021-01-05 23:55

Do you know how to manually resolve dependencies in .net core? Something like

DependencyResolver.Resolve()
相关标签:
1条回答
  • 2021-01-06 00:33

    Add your dependency in ConfigureServices as below

    public void ConfigureServices(IServiceCollection services){
        //AddSingleton or AddTransient based on your requirements
        services.AddTransient<ISomeService, ConcreteService>();
    }
    

    In your controller or anywhere, add IServiceProvider in the constructor like below:

    using Microsoft.Extensions.DependencyInjection;
    
    ...
    
    public class HomeController
    {
      ...
      public HomeController(IServiceProvider serviceProvider)
      {
          var service = serviceProvider.GetService<ISomeService>();
      }
    }
    

    @Shazam, Here are some notes or suggestions based on your comment:

    • If you can not inject because you might not have a constructor in this class, I woud suggest to add a paramter to your function and pass the resolved dependency from outside

    • Another Idea is to add a static property and initialize its value in ConfigureServices

    For Example:

    public static class MyClass
    {
        public static ISomeService MyServiceObj { set; get; }
        ....
    }
    

    In your ConfigureServices

       public void ConfigureServices(IServiceCollection services){
            services.AddTransient<ISomeService, ConcreteService>();
            MyClass.MyServiceObj = services.GetService<ISomeService>();
        }
    

    Hope this helps, please rate my answer or leave me a comment if you still in doubt how to do it

    0 讨论(0)
提交回复
热议问题