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

时间:2016-06-08 16:08:23

标签: c# interface autofac

我创建了通用接口,假设将实体映射到视图模型和向后。我必须在autofac配置中进行大约80次注册。是否可以将它们注册为批次? 这是界面:

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

谢谢!

4 个答案:

答案 0 :(得分:25)

您可以使用:

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

其中assemblies是您的类型所属的程序集的集合。

如果您的PersonMapper继承自ICommonMapper<Person, PersonModel, Int32>,则 Autofac 将能够解析ICommonMapper<Person, PersonModel, Int32>

答案 1 :(得分:4)

不需要让它变得复杂,你只需要正常注册接口的所有实现,如下所示:

enter image description here

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

我使用了这种方法,它完全符合我的预期。希望能帮助到你。干杯

答案 2 :(得分:0)

这是另一种方法,但在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();
        }

答案 3 :(得分:-1)

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

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

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