如何在构造函数中解析类型安全集合?

时间:2018-09-22 00:32:51

标签: c# .net dependency-injection ioc-container simple-injector

我有这个对象结构

public interface IHandler<in TMessage>
{
    void HandleMessage(TMessage messageType);
}

public class MessageType1
{
}

public class MessageType2
{
}

public class HandlerMessageType1 : IHandler<MessageType1>
{
    public void HandleMessage(T messageType)
    {
    }
}

public class HandlerMessageType2 : IHandler<MessageType2>
{
    public void HandleMessage(T messageType)
    {
    }
}

和注册

container.Collection.Register(typeof(IHandler<>), new[]
        {
            typeof(HandlerMessageType1),
            typeof(HandlerMessageType2)
        });

注入它的类的构造函数应如何?

  public class ClientClass
  {
     public ClientClass(IEnumerable<IHandler<>> handlers)
     {
     }
  }

像这样不起作用...客户端类构造函数的签名应该是什么样子?

对此进行了编辑以改进示例。

提前tkx

Paulo Aboim Pinto

1 个答案:

答案 0 :(得分:0)

我知道我是否理解,但是团结一致,您可以:

public class Handler1 : IHandler
{
    public void HandlerType()
    {
        Console.WriteLine("Handler1");
   }
}

public class Handler2 : IHandler
    {
        public void HandlerType()
        {
            Console.WriteLine("Handler2");
        }
    }

public interface IHandler
    {
        void HandlerType();
    }

统一配置

public static class DependencyConfiguration

{
    public static UnityContainer Config()
    {
        var unity = new UnityContainer();
        unity.RegisterType<IHandler, Handler1>("Handler1");
        unity.RegisterType<IHandler, Handler2>("Handler2");
        unity.RegisterType<IEnumerable<IHandler>>();


        return unity;
    }
}

要解决的课程:

public class ListOfTypes
    {
        private List<IHandler> handlers;
        public ListOfTypes(IEnumerable<IHandler> handlers)
        {
            this.handlers = handlers.ToList();
        }

        public void PrintHandlers()
        {
            handlers.ForEach(_ => _.HandlerType());
        }

    }

程序:

 static void Main(string[] args)
        {
            Console.WriteLine("Resolve sample");
            var unity = DependencyConfiguration.Config();
            var lstOfTypes = unity.Resolve<ListOfTypes>();

            lstOfTypes.PrintHandlers();

            Console.ReadLine();
        }

结果:

enter image description here