CodeBlanks Logo Icon CodeBlanks

Summary - Reflection

C# course · Advanced · Lesson 48/83

Combine Type, Activator and Invoke to write a simple DI container.

Summary - Reflection

In this group you learned Type, Activator.CreateInstance, MethodInfo.Invoke and PropertyInfo. Combining these, you can write a simple DI container that produces instances from type names and invokes methods.

First you will build a small Container that maps an interface to an implementation; then you will make a dynamic method call via reflection. This is the basis of real DI containers and serializers.

Exercise Simple DI container: the Resolve method

Write the body of Resolve<TInterface>() in the Container class below. Create an instance with Activator.CreateInstance(map[typeof(TInterface)]) and cast it to (TInterface) before returning. The Main body is complete; only fill the Resolve body.

Show example solution
return (TInterface)Activator.CreateInstance(map[typeof(TInterface)]);
Example solution:
using System;
using System.Collections.Generic;
using System.Reflection;

interface IGreeter { void Greet(); }

class HelloGreeter : IGreeter
{
    public void Greet() => Console.WriteLine("Hello");
}

class Container
{
    private Dictionary<Type, Type> map = new Dictionary<Type, Type>();
    public void Register<TInterface, TImpl>() where TImpl : TInterface
        => map[typeof(TInterface)] = typeof(TImpl);
    public TInterface Resolve<TInterface>()
    {
        return (TInterface)Activator.CreateInstance(map[typeof(TInterface)]);
    }
}

class Program
{
    static void Main()
    {
        Container c = new Container();
        c.Register<IGreeter, HelloGreeter>();
        IGreeter g = c.Resolve<IGreeter>();
        g.Greet();
    }
}

Exercise Invoke a command method

In the Greeter class below, get the method with MethodInfo mi = typeof(Greeter).GetMethod("Say");. Call it with mi.Invoke(g, new object[] { "Ayşe" });.

Show example solution
mi.Invoke(g, new object[] { "Ayşe" });
Example solution:
using System;
using System.Reflection;

class Greeter
{
    public void Say(string name) => Console.WriteLine($"Hello, {name}!");
}

class Program
{
    static void Main()
    {
        Greeter g = new Greeter();
        MethodInfo mi = typeof(Greeter).GetMethod("Say");
        mi.Invoke(g, new object[] { "Ayşe" });
    }
}

Test yourself

  1. What does Activator.CreateInstance return?

    • A MethodInfo
    • A PropertyInfo
    • A Type object
    • An object instance
    Show answer

    An object instance — Correct. Activator.CreateInstance returns an object instance.

  2. Match the method to its purpose

    typeof(T)
    Gets a Type
    Activator.CreateInstance
    Creates an instance
    MethodInfo.Invoke
    Calls a method
    PropertyInfo.GetValue
    Reads a property

All lessons in Advanced