Search code examples
c#unity-containercqrs

Unity Auto Register ICommandHandler


What about, I have a several classes that implement the ICommanHandler <> interface several times, as I can do with Unity to register them automatically and not one by one. Thank you.

public class CarCommandHandler:ICommandHandler<CreateCar>
                               ICommandHandler<DeleteCar>
{
    ......
}


public class EngineCommandHandler:ICommandHandler<CreateEngine>
                                  ICommandHandler<DeleteEngine>
{
    ......
}



public static void RegisterTypes(IUnityContainer container)
{
   container.RegisterType<ICommandHandler<CreateCar>, CarCommandHandler>();

   container.RegisterType<ICommandHandler<DeleteCar>, CarCommandHandler>();

   container.RegisterType<ICommandHandler<CreateEngine>, EngineCommandHandler>();

   container.RegisterType<ICommandHandler<DeleteEngine>, EngineCommandHandler>(); 
}

Solution

  • You need to iterate all of types that implement ICommandHandler<> and register them. Code is below can do that:

        public static void RegisterAllImplementations(this UnityContainer container, Type openInterfaceType)
        {
            int registerCount = 0;
            // Iterate all types from current assembly
            foreach (var typeItem in Assembly.GetExecutingAssembly().GetTypes())
            {
                foreach (var interaceItem in typeItem.GetInterfaces())
                {
                    if (interaceItem.IsGenericType && interaceItem.GetGenericTypeDefinition() == openInterfaceType)
                    {
                        container.RegisterType(interaceItem, typeItem, $"{registerCount++}");
                    }
                }
            }
        }
    

    An invocation:

        var container = new UnityContainer();
        container.RegisterAllImplementations(typeof(ICommandHandler<>));
    

    Let me know if something doesn't work