concept reflection in category dependency injection
appears as: reflection, reflection

This is an excerpt from Manning's book Dependency Injection.
By pulling the type name from the application configuration file and creating a
Typeinstance from it, you can use reflection to create an instance ofIMessageWriterwithout knowing the concrete type at compile time. To make this work, you specify the type name in themessageWriterapplication setting in the application configuration file:
Listing 10.16 Implementing a generic auditing aspect for business operations
public class AuditingCommandServiceDecorator<TCommand> : ICommandService<TCommand> { private readonly IUserContext userContext; private readonly ITimeProvider timeProvider; private readonly CommerceContext context; private readonly ICommandService<TCommand> decoratee; public AuditingCommandServiceDecorator( IUserContext userContext, ITimeProvider timeProvider, #1 CommerceContext context, ICommandService<TCommand> decoratee) { this.userContext = userContext; this.timeProvider = timeProvider; this.context = context; this.decoratee = decoratee; } public void Execute(TCommand command) { this.decoratee.Execute(command); this.AppendToAuditTrail(command); } private void AppendToAuditTrail(TCommand command) { var entry = new AuditEntry #2 { #2 UserId = this.userContext.CurrentUser.Id, #2 TimeOfExecution = this.timeProvider.Now, #2 Operation = command.GetType().Name, #2 Data = Newtonsoft.Json.JsonConvert #2 .SerializeObject(command) #2 }; this.context.AuditEntries.Add(entry); this.context.SaveChanges(); } } #1 Recall that this is the ITimeProvider interface from listing 5.10. #2 Besides appending the user and the time of execution to the audit trail, the Decorator stores the name of the command and a serialized representation of its data too. This information is gathered using reflection and, in this case, you use the well-known JSON.NET serialization library (https://www.newtonsoft.com/json) that converts the command data to a readable JSON format.
Figure 12.2 Simplified workflow for Auto-Wiring. A DI Container uses its configuration to find the appropriate concrete class that matches the requested type. It then uses reflection to examine the class’s constructor.
![]()