Ticker

6/recent/ticker-posts

Constructor Injection in Unity Container

Constructor Injection in Unity Container

Introduction: Constructor injection is a widely used technique in dependency injection frameworks, including Unity Container. It allows you to provide dependencies to a class through its constructor, ensuring that the dependencies are resolved and passed automatically by the container. This promotes loose coupling and improves testability and maintainability of your code.

Code Example: Here's an example that demonstrates constructor injection in Unity Container using C#:

csharp
using Microsoft.Practices.Unity; public interface ILogger { void Log(string message); } public class ConsoleLogger : ILogger { public void Log(string message) { Console.WriteLine(message); } } public class CustomerService { private readonly ILogger _logger; public CustomerService(ILogger logger) { _logger = logger; } public void ProcessCustomer(string customerName) { _logger.Log("Processing customer: " + customerName); // Rest of the code } } class Program { static void Main(string[] args) { // Create Unity Container IUnityContainer container = new UnityContainer(); // Register dependencies container.RegisterType<ILogger, ConsoleLogger>(); // Resolve and use the dependency CustomerService customerService = container.Resolve<CustomerService>(); customerService.ProcessCustomer("John Doe"); // Dispose the container when done container.Dispose(); } }

Explanation: In the code example above, we have defined an interface ILogger and its implementation ConsoleLogger. The CustomerService class has a dependency on the ILogger interface, which is injected through its constructor.

In the Main method, we create an instance of the Unity Container (IUnityContainer). Then, we register the ILogger interface with its concrete implementation ConsoleLogger using container.RegisterType<ILogger, ConsoleLogger>(). This tells the container how to resolve the ILogger dependency when requested.

Next, we resolve the CustomerService class from the container using container.Resolve<CustomerService>(). The container automatically resolves the ILogger dependency and injects it into the CustomerService constructor.

Finally, we can use the CustomerService instance and call its methods, such as ProcessCustomer("John Doe"). The ILogger dependency is already provided by the container, allowing the CustomerService class to function correctly.

Remember to dispose of the container when it's no longer needed using container.Dispose().

Constructor injection using Unity Container simplifies the process of managing dependencies and promotes cleaner and more modular code. It also enables easier testing by allowing you to easily mock or substitute dependencies during unit tests.

Post a Comment

0 Comments