如何注册 >在简单的喷射器中

问题描述 投票:0回答:1

我正在尝试将cqrs实现到我的系统中,如何在简单的注入器中注册Generic集合?当我尝试运行我的代码时,我得到了异常请使用其他一个重载来注册这种类型。

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

c# simple-injector
1个回答
0
投票

如果您的处理程序是泛型,您可以尝试使用以下逻辑添加它们,首先使用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);
© www.soinside.com 2019 - 2024. All rights reserved.