Generic Interfaces with Unity

merous times we have a generic interface with their concrete implementations. An example would be something like:

public interface IAnimalSound<T> {
  string Sound();
public class CatSound : IAnimalSound<Cat> {
    public string Sound() => "Meow";
public class DogSound: IAnimalSound<Dog> {
    public string Sound() => "Woof woof";

The idea is that, we would like Unity to be able to resolve: IAnimalSound<Cat> to CatSound and IDogSound<Dog> to DogSound so that we could do:

var catSound = container.Resolve<IAnimalSound<Cat>>().Sound(); // Meow
var dogSound = container.Resolve<IAnimalSound<Dog>>().Sound(); // woof woof

A quick unity type register would be something like:

container.RegisterType<IAnimalSound<Cat>, CatSound>(...);
container.RegisterType<IAnimalSound<Dog>, DogSound>(...);

But the solution above would not be suitable, especially if we want to have many multiple implementations of IAnimalSound.

In order to do that, we can do the following below:

    .Where(t => t.GetInterfaces().Any(i => i.IsGenericType && 
    i.GetGenericTypeDefinition() == typeof(IAnimalSound<>))), 

The above registration will register all instances of IAnimalSound<…> to its implementation.

2 thoughts on “Generic Interfaces with Unity

  1. Pingback: Leveraging DI with Command Pattern (C# / MVC) | Code Construct

  2. Pingback: DRY-ing code with Command Handler | Code Construct

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s