I have a class with a constructor that looks like the following:
public BatchService(IRepository repository, ILogger logger, string user)
In my DI bootstrapper class, I have the following RegisterType
command:
.RegisterType<BatchService>(
new InjectionConstructor(
new ResolvedParameter<IRepository>("SomeRepository"),
new ResolvedParameter<ILogger>("DatabaseLogger")))
In my client code, I want to instantiate BatchService
as follows:
BatchService batchService = DIContainer.Resolve<BatchService>()
As you can see, I have a string parameter called user
as part of the constructor to BatchService
that is not part of the DI logic. How should I best handle this situation if I need to use user
in the BatchService
class?
Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class. @Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.
A class that lets you specify a factory method the container will use to create the object.
A class that holds the collection of information for a constructor, so that the container can be configured to call this constructor.
Please don't abuse Unity as a ServiceLocator.
If you want to create objects that need runtime parameters use a factory. You can even drop the act of implementing that factory by either using the Unity version of Typed Factories or let Unity generate factory delegates for you.
You can use ParameterOverride
:
BatchService batchService =
DIContainer.Resolve<BatchService>(new ParameterOverride("user", valueForUser));
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