如何在简单的注射器中注册<Func<Type,IEnumerable<T>>



我正在尝试在我的系统中实现 cqrs,以及如何在简单注入器中注册泛型集合?当我尝试运行代码时,出现异常 请使用其他重载之一来注册此类型。

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" });

如果你的处理程序是泛型,你可以尝试使用以下逻辑添加它们,首先使用 GetTypesToRegister 获取它们,然后注册为集合

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

最新更新