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....
}
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With