Unity Container: Constructor Injection
Back to: Software Development Principles
Constructor injection is one of the most commonly used forms of dependency injection, and Unity Container provides full support for constructor injection.
To use constructor injection with Unity Container, you can register the types with the container using the RegisterType
method and specify the constructor parameters in the registration. For example:
container.RegisterType<ICustomerRepository, CustomerRepository>(); container.RegisterType<IOrderService, OrderService>( new InjectionConstructor( new ResolvedParameter<ICustomerRepository>(), new ResolvedParameter<IOrderRepository>() ));
In this example, we are registering the ICustomerRepository
and IOrderService
types with the container. We are specifying the constructor parameters for the OrderService
type using the InjectionConstructor
method. The ResolvedParameter
method is used to specify that the ICustomerRepository
and IOrderRepository
dependencies should be resolved by the container.
When we resolve the IOrderService
dependency using the container, Unity will automatically inject the ICustomerRepository
and IOrderRepository
dependencies into the OrderService
constructor.
var orderService = container.Resolve<IOrderService>();
In addition to the ResolvedParameter
method, Unity Container provides a number of other ways to specify constructor parameters, including specifying values directly or using named or typed parameters.
container.RegisterType<IOrderService, OrderService>( new InjectionConstructor( "OrderService", new ResolvedParameter<ICustomerRepository>(), new ResolvedParameter<IOrderRepository>() ));
container.RegisterType<IOrderService, OrderService>( new InjectionConstructor( new InjectionParameter("OrderService"), new ResolvedParameter<ICustomerRepository>(), new ResolvedParameter<IOrderRepository>() ));
container.RegisterType<IOrderService, OrderService>( new InjectionConstructor( new ResolvedParameter<ICustomerRepository>(), new ResolvedParameter<IOrderRepository>(), new ResolvedParameter<string>("OrderService") ));
In summary, Unity Container provides full support for constructor injection, allowing you to specify constructor parameters in the type registration and automatically injecting dependencies into the constructor when the type is resolved.