Home » C# » Unity – Constructors with Parameters

Unity – Constructors with Parameters

Microsoft Unity is a great library to use for a dependency injection container. It has support for constructor, property, and method call injection. Typically you’ll use constructor injection. I wanted to use it for a class whose constructor took parameters. Here’s an example I’ve created to show what I wanted to do:

First I have an interface for logging – ILogger:

Then I have an actual class that implements this interface – FileLogger:

In my program I create the Unity container. I then want to register my FileLogger class as an implementation of the ILogger interface. This part would be straightforward to do, but what happens when I use Resolve on the container? The constructor takes parameters. Where do we specify those? It turns out that we do this at the point that we do the registration. We can use the InjectionConstructor class to provide those parameters. Here’s how we would do it: