2016-06-08 1 views
4

모델을 보거나 뒤로 보도록 엔티티를 매핑한다고 가정하는 일반적인 인터페이스를 만들었습니다. 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

답변

17

당신은 사용할 수 있습니다 assemblies이 유형에 속하는 어셈블리의 모음입니다

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

.

당신은 ICommonMapper<Person, PersonModel, Int32>에서 상속 PersonMapper, Autofac 여기

+0

은 IAssemblyFinder ...와 함께 작성자를 제공해야했습니다. – Roman

0

인터페이스를 구현하는 모든 것을 등록하도록 autofac에 지시 할 수 있습니다. 여러 dll에서 많은 것을로드해야하므로 이렇게 조정 했으므로 자신의 필요에 맞게 조정할 수 있어야합니다.

여기에 예제가 있습니다. 사용자의 필요에 맞게 조정할 수 있습니다.

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

ICommonMapper<Person, PersonModel, Int32>이 할 수있는 또 다른 방법입니다 해결 할 수있는 경우 만 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(); 
     } 
1

하지 마십시오 복잡하게 만들 필요가있는 경우 아래와 같이 정상적으로 인터페이스의 모든 구현을 등록하면됩니다.

enter image description here

그런 다음 Autofac은 이와 같은 생성자에서 인터페이스의 열거 형/배열을 볼 때 해당 인터페이스의 구현을 자동으로 주입합니다. enter image description here

나는이 방법을 사용하여 예상대로 완벽하게 작동합니다. 희망이 도움이됩니다. 건배

+1

'IEnumerator '에 대한 참조를 캡처하지만 처리하지 않으면 해당 코드에서 메모리 누수가 발생합니다. 클래스가'IDisposable '을 구현하지 않아서 사용하지 않았다고 가정합니다. 이 방법을 선택하고 'IEnumerable '필드를 유지하지 않기로 결정한 이유를 설명해 주시겠습니까? –

+0

안녕하세요 믹, 귀하의 의견에 감사드립니다, 나는 우리가 그 인스턴스를 처리 할 필요가 동의하지만, 여기 내 대답의 초점 아니 었어. Autofac을 사용하여 특정 인터페이스의 구현 배열을 특정 인스턴스에 주입하는 방법에 대한 예제를 제공하고자했습니다. IEnumerable 필드를 유지하지 않으려면 ICommandChainFeature의 구현을 CommandChain 클래스에 삽입해야하기 때문에 :) –

+1

하지만 IEnumerator 대신 'private readonly IEnumerable _features; ? –