如何在autofac中注册通用接口的所有实现?

问题描述:

我已经创建了通用接口,假设它映射实体以查看模型并向后。我必须在autofac配置中进行大约80次注册。是否有可能将它们注册为批处理? 这里是接口:如何在autofac中注册通用接口的所有实现?

public interface ICommonMapper<TEntity, TModel, TKey> 
    where TEntity : BaseEntity<TKey> 
    where TModel : BaseEntityViewModel<TKey> 
    where TKey : struct 
{ 
    TModel MapEntityToModel(TEntity entity); 
    TModel MapEntityToModel(TEntity entity, TModel model); 
    TEntity MapModelToEntity(TModel model); 
    TEntity MapModelToEntity(TModel model, TEntity entity); 
} 

谢谢!

+2

你有80个'ICommonMapper'的实现吗? –

+0

约80. 117个实体类型...和其中约80个是CRUDable – Roman

你可以使用:

builder.RegisterAssemblyTypes(assemblies) 
     .AsClosedTypesOf(typeof(ICommonMapper<,,>)); 

哪里assemblies是你的类型属于该集的收集。

,如果你有一个PersonMapperICommonMapper<Person, PersonModel, Int32>继承,Autofac就能解决ICommonMapper<Person, PersonModel, Int32>

+0

必须提供IAssemblyFinder ...工作的生成器。 – Roman

您可以告诉autofac注册实现接口的所有内容。我不得不从几个DLL加载很多东西,所以我做了这样的事情,你应该可以根据自己的需要进行调整:

这里有一个例子,你应该能够根据自己的需要进行调整:

foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) 
      { 
       if (assembly.FullName.Contains("someNameYouCareAbout")) 
       { 
        builder.RegisterAssemblyTypes(assembly) 
        .AsImplementedInterfaces(); 
       } 
      } 

这里是另一种方式来做到这一点,但与typeFinder的帮助:

var mappers = typeFinder.FindClassesOfType(typeof(ICommonMapper<,,>)).ToList(); 
     foreach (var mapper in mappers) 
     { 
      builder.RegisterType(mapper) 
       .As(mapper.FindInterfaces((type, criteria) => 
       { 
        var isMatch = type.IsGenericType && 
            ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition()); 
        return isMatch; 
       }, typeof(ICommonMapper<,,>))) 
       .InstancePerLifetimeScope(); 
     } 

不要需要使其变得复杂,您只需简单地注册一个接口的所有实现,如下所示:

enter image description here

然后Autofac会自动注入该接口的实现,当它看到接口的enumerable /数组在这样的构造函数中。 enter image description here

我使用了这种方法,它的工作原理与我所期望的完全一样。希望能帮助到你。干杯

+1

在捕获对IEnumerator的引用时,代码中存在内存泄漏,但不要处理它 - 我假设你没有,因为你的类没有实现'IDisposable'。你会不会在乎解释为什么你选择这种方式,而不是保留'IEnumerable '字段? –

+0

嗨米克,感谢您的评论,我同意我们需要处理这些实例,但这不是我在这里的答案的焦点。我只想给你们一个例子,说明如何使用Autofac将特定接口的实现数组注入特定实例。为了不保留一个IEnumerable 字段,因为我只是想将ICommandChainFeature的实现注入到我的CommandChain类中:) –

+1

我明白了,但为什么没有'private readonly IEnumerable _features;'而不是'IEnumerator ? –