Search code examples
c#simple-injector

How to Register<Func<Type, IEnumerable<T>> in simple injector


I am trying to implement cqrs to my system and How can i register Generic collection in simple injector? When i trying what i run my code i got exception Please use one of the other overloads to register this type.

public class Ioc
  {
      public static SimpleInjector.Container Container;

      static Ioc()
      {
          Container = new SimpleInjector.Container();

          Container.Register<IHandleEvent, Handler>(Lifestyle.Transient);
          Container.Register<ICommandsBus, CommandsBus(Lifestyle.Transient);
          Container.Register<IEventsBus, EventsBus>(Lifestyle.Transient);
          Container.Register<Func<Type, IEnumerable<IHandleEvent>>> (Lifestyle.Transient);
      }
  }

//Without any Conatiner working

List<Handler> handlers = new List<Handler>();
          Handler handler = new Handler();
          handlers.Add(handler);
          Func<Type, IEnumerable<IHandleEvent>> func = f => handlers;
          EventsBus eventsBus = new EventsBus(func);
          eventsBus.Publish(new User { Id = 1, Login = "Test" });

// I want something like this
 var bus = Ioc.Container.GetInstance<IEventsBus>();
          bus.Publish(new User { Id = 1, Login = "tt" });


Solution

  • if your handlers are generics you can try add them with the following logic, firstly get them with GetTypesToRegister and then register as a collection

      // assemblies - assemblies with your handlers 
    
    var notificationHandlerTypes = 
        Container.GetTypesToRegister(typeof(IHandleEvent<>), assemblies, new 
            TypesToRegisterOptions
            {
                IncludeGenericTypeDefinitions = true,
                IncludeComposites = false,
            });
    Container.Collection.Register(typeof(IHandleEvent<>), notificationHandlerTypes);