Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity constructor injection with other parameter

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?

like image 312
EverettE Avatar asked Aug 16 '12 20:08

EverettE


People also ask

What does @inject do with constructor?

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.

What is Injectionfactory?

A class that lets you specify a factory method the container will use to create the object.

What is Injectionconstructor?

A class that holds the collection of information for a constructor, so that the container can be configured to call this constructor.


2 Answers

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.

like image 156
Sebastian Weber Avatar answered Oct 05 '22 00:10

Sebastian Weber


You can use ParameterOverride:

BatchService batchService = 
DIContainer.Resolve<BatchService>(new ParameterOverride("user", valueForUser));
like image 27
Suresh Avatar answered Oct 05 '22 00:10

Suresh