简体   繁体   English

使用Unity自动注册所有接口

[英]Auto-register all interfaces with Unity

Using Unity, I'd like to automatically register all interface/class combinations in an assembly based on the following convention: 使用Unity,我想根据以下约定自动注册程序集中的所有接口/类组合:

INameOfObject > NameOfObject

StructureMap does that when the default conventions are enabled. 当启用默认约定时,StructureMap会执行此操作。

I wrote the following method for it: 我为它写了以下方法:

private static IUnityContainer RegisterITypesOf(this IUnityContainer container, string assemblyName)
{
  Assembly.Load(assemblyName)
    .GetTypes()
    .Where(t => t.GetInterfaces().Any(i => i.Name == "I" + t.Name))
    .ForEach(t => container.RegisterType(t.GetInterface("I" + t.Name, false), t));
  return container;
}

My question is: 我的问题是:

  • is there a built-in function that does the same? 是否有一个内置函数做同样的事情?
  • if not, can my code be improved performance wise? 如果没有,我的代码可以改进性能吗?

Unity 3.5.140.0 has built in functionality to register interfaces with similar names as the class that uses it. Unity 3.5.140.0内置了注册接口的功能,其名称与使用它的类相似。

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterTypes(
    AllClasses.FromLoadedAssemblies(),
    WithMappings.FromMatchingInterface,
    WithName.Default);
}

I wanted the same as you; 我想和你一样; convention based configuration ala Structuremap, and went ahead and created a library for it. 基于约定的配置ala Structuremap,并继续为它创建了一个库。 You can download it on NuGet , and read some documentation on my github page 您可以在NuGet上下载它,并在我的github页面上阅读一些文档

Hope this helps! 希望这可以帮助!

Unity does not have support for conventions. Unity不支持约定。 But the TecX project on codeplex contains an enhanced configuration engine for Unity that is based on StructureMap's configuration. 但是Codeplex上TecX项目包含一个基于StructureMap配置的Unity增强配置引擎

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM