代码之家  ›  专栏  ›  技术社区  ›  LastTribunal

不需要登记的国际奥委会集装箱

  •  -6
  • LastTribunal  · 技术社区  · 7 年前

    有这样的事吗? 如果我所要做的就是解决 小精灵 事情 ,为什么我需要创建一个注册?我应该在运行时动态映射。我可以很容易地创建一个有反射的…但希望避免建立我自己的…

    我正在像往常一样解决问题。不需要注册就可以轻松处理反射。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Steven    7 年前

    你要找的是 自动注册 . 大多数容器允许您在基于 惯例 或者执行未注册的类型解析并查找缺少的类型。

    例如,可以搜索程序集并注册启动期间与约定匹配的所有类型:

    var container = new Container();
    
    Assembly assembly = typeof(Thing).Assembly;
    
    var mappings =
        from type in assembly.GetExportedTypes()
        let matchingInterface = "I" + type.Name
        let service = type.GetInterfaces().FirstOrDefault(i => matchingInterface)
        where service != null
        select new { service, type };
    
    foreach (var mapping in mappings)
    {
        // Register the type in the container
        container.Register(mapping.service, mapping.type);
    }
    

    使用未注册的类型解析,您可以动态注册。如何做到这一点在很大程度上取决于您使用的容器。例如,对于简单的注入器,如下所示:

    var container = new Container();
    
    Assembly assembly = typeof(Thing).Assembly;
    
    container.ResolveUnregisteredType += (s, e)
    {
        Type service = e.UnregisteredServiceType;
        if (service.IsInterface)
        {
             var types = (
                 from type in asssembly.GetExportedTypes()
                 where service.IsAssignableFrom(type)
                 where !type.IsAbstract
                 where service.Name == "I" + type.Name
                 select type)
                 .ToArray();
    
             if (types.Length == 1)
             {
                 e.Register(Lifestyle.Transient.CreateRegistration(types[0], container));
             }          
        }
    };
    

    这两种方法都不需要不断更新容器配置。