0

제품 가져 오기 모듈 (NopCommerce3.9 플러그인)에서 작업하고 있는데, 100 가지 이상의 가져 오기 형식이 있습니다. 수입 방법 내가 만든 하나의 IFormat 인터페이스는 각각의 새로운 형식의 클래스는 IFormat를 구현하고 수입에 대한 자신의 논리를 제공 할 것입니다Autofac Dependency Injection 프레임 워크에서 많은 클래스를 하나의 인터페이스에 등록하고 해결하는 방법

interface IFormat 
{ 
    bool Import(file) 
} 

class Format_A : IFormat 
{ 
public bool Import(file) 
    //import with A format 
} 

class Format_B : IFormat 
{ 
public bool Import(file) 
    //import with B format 
} 

나는 형식 유형 autofac에/클래스 아래로 등록했습니다

public class DependencyRegistrar 
{ 
    public virtual void Register(Autofac_Container builder) 
    { 
      builder.RegisterType<Format_A>().AsSelf().InstancePerLifetimeScope(); 
      builder.RegisterType<Format_B>().AsSelf().InstancePerLifetimeScope(); 
    } 
} 

가져 오기 작업을 실행하면 config에서 현재 형식을 읽습니다. FormatFactory.GetFormat() 메서드에 전달합니다.

public ActionResult ImportExcel() 
{ 
    var format=format_from_config; 
    var file = Request.InputStream; 
    IFormat currentFormat = FormatFactory.GetFormat(format); 
    bool success = currentFormat.Import(file); 
    return Json(new { success = success }); 
} 

FormatFactory는 전달 된 format 매개 변수에서 새 개체베이스를 확인하거나 작성합니다. 이제 Autofac 의존성 프레임 워크

class FormatFactory 
{ 
    public static IFormat GetFormat(string format) 
    { 
     switch (format) 
     { 
      case "Format_A": 
       return Autofac_Container.Resolve<Format_A>(); 
      case "Format_B": 
       return Autofac_Container.Resolve<Format_B>(); 
      default: 
       throw new ArgumentException($"No Type of {nameof(format)} found by factory", format); 
     } 
    } 
} 

를 사용 , 공장에서 switch 문을 제거 할 수있는 방법이있다. 나는 리플렉션을 사용하여 그것을 할 수 있지만 Format 클래스에는 (실제 코드에서) 다른 의존성이있다. 그래서, Autofac에서 이것을 달성 할 수있는 방법이 있으며, 마찬가지로 클래스의 문자열 이름으로 유형을 분석 할 수 있습니다. 내가 코드를 아래와 같이

Autofac의 이름을 지원
public class DependencyRegistrar 
    { 
     public virtual void Register(Autofac_Container builder) 
     { 
       builder.RegisterType<Format_A>().As<IFormat>().Resolve_If_String_Name_like("Format_A").InstancePerLifetimeScope(); 
       builder.RegisterType<Format_B>().As<IFormat>()Resolve_If_String_Name_like("Format_B").InstancePerLifetimeScope(); 
     } 
    } 
------------------------------------------------------------------- 
class FormatFactory 
{ 
    public static IFormat GetFormat(string format) 
    { 
     return Autofac_Container.Resolve<IFormat>("Format_A"); 
    } 
} 

답변