Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string along with an injected dependency in ASP.NET Core v2

I have the below method in my Startup.cs class of my ASP.NET Core v2 project. My question is how to setup a class/service where a string value is passed to a class, along with an injected dependency.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add custom services.
        services.AddSingleton<IMyAssistantClass, MyAssistantClass);
        services.AddSingleton<MyClassManager>(s => new  MyClassManager("connectionString", /* How to inject IMyAssistantClass? */);

        // Other setup....
    }
like image 749
contactmatt Avatar asked Jun 13 '18 07:06

contactmatt


1 Answers

public void ConfigureServices(IServiceCollection services)
{
  services.AddSingleton<IMyAssistantClass, MyAssistantClass);
  services.AddSingleton<MyClassManager>(s => 
    {
      var imy = (IMyAssistantClass) s.GetService(typeof(IMyAssistantClass))
      new  MyClassManager("connectionString", imy);
    }
  );
}

// nice way to make it more convenient is to add extension method to IServiceCollection, like

public static T Resolve<T>(this IServiceProvider serviceProvider)
{
    return (T) serviceProvider.GetService(typeof(T));
}

and then you could just call s.Resolve<IMyAssistantClass>();

like image 187
djaszczurowski Avatar answered Sep 28 '22 09:09

djaszczurowski