I have a class with below constructor:
public MyClass(SomeRequiredService srs, string someRandomInput)
{
}
How can I register MyClass with DI but with an option to pass a different someRandomInput each time i need to get an instance of MyClass?
or
With below constructor how can I get access to registered services or IServiceProvider in MyClass ctor while having a dynamic parameter in constructor?
public MyClass(string someRandomInput)
{
// how access a registered service here using DI?
}
Assuming
someRandomInputonly needs to be specified once, then you can do this in animplementationFactory:in your service registration:The same works for
AddTransientandAddScoped- the catch being that they'll all use whatever value you pass intosomeRandomInputin your factory - though your factory method itself could also use theIServiceProviderto get another service as a source for those values.More generalised, here's two approaches:
Option 1: Define an interface that represents your services' data-dependency
...then you'd register some implementation of that
Requisiteservice interface.Option 2: Not-quite-as-bad-as
AbstractSingletonProxyFactoryBean(In case anyone missed the reference)
and it's factories all the way down...
I was surprised that MEDI still lacks a standardised
IServiceFactoryinterface to handle the awkward edge-cases that need more factory-logic than a simplesp =>lambda, but which don't need to explicitly call their.CreateService()methods in application code - especially as EF already has its ownIDbContextFactorytype.Update: Option 3: Factory-service-with-caller-provided-args
After clarifying things in the comments, I think the OP is after something like this:
FoobarServiceFactory(or aninterfacethereof) is a normal Singleton service which carries theFoobarServicedependencies - but also allows/requires the consumers ofFoobarServiceFactoryto provide their own arguments for when they want to get an instance ofFoobarService, like so:Used like so:
An alternative implementation of
IFoobarServiceFactorycould useIServiceProvider, if it isn't possible to retain a long-life'd (or unbound lifetime) forSomeRequiredService(and IMO, this is the only acceptable reason to ever needIServiceProvideras an actual dependency (other than breaking cycles in dependency graphs, ofc):