I think the explanations in this article are quite good:
Complex services might require additional services. In the following
example, DataAccess requires the HttpClient default service. @inject
(or the [Inject] attribute) isn't available for use in services.
Constructor injection must be used instead. Required services are
added by adding parameters to the service's constructor.
You are on the right track here:
public GSP(HttpClient httpClient)
{
this.httpClient = httpClient;
}
But this is where you are mistaken
but then i have to pass this httpClient manualy that was injected into
component for example.
Don't pass anything manually. Instead inject your GSP
class into your component.
in your razor component base class:
[Inject]
public GSP myGspService { get; set; }
or directly in the razor file:
@Inject GSP myGspService
If you want a new instance each time you use it, inject a GSPFactory
class. You cannot inject non-registered parameters (such as your "db1" and "table1") using DI directly, the factory class would have to deal with that, or you would have to set them each timeyou create it..
in your razor component base class:
[Inject]
public GSPFactory myGspService { get; set; }
or directly in the razor file:
@Inject GSPFactory myGspService
and your factory class:
public class GSPFactory {
Func<GSP> iocFactory;
public GSPFactory(Func<GSP> iocFactory) {}
this.iocFactory = iocFactory;
}
public GSP Create(string option1, string option2) {
var gsp = this.iocFactory();
gsp.Option1 = option1;
gsp.Option2 = option2;
return gsp;
}
}
The setup could look like this:
Services.AddTransient<GSP>()
.AddTransient<Func<GSP>>(x => () => x.GetService<GSP>())
.AddSingleton<GSPFactory>() // (... plus httpClient etc)
factory class variant if you insist on having an injected property:
public class GSPFactory {
HttpClient httpClient;
public GSPFactory(HttpClient httpClient) {}
this.httpClient= httpClient;
}
public GSP Create(string option1, string option2) {
var gsp = new GSP(option1, option2);
gsp.HttpClient= httpClient;
return gsp;
}
}
The setup could then simply look like this:
Services.AddSingleton<GSPFactory>() // (... plus httpClient etc)
In any case, you would always inject the factory, and get a new instance of GSP like this:
injectedGspFactory.Create("db1", "table1");