0

私は製品インポートモジュール(NopCommerce3.9プラグイン)で作業していますが、100以上のインポートフォーマットを持っています。私はので、それぞれの新しい形式のクラスは、私がAutofac Dependency Injection Frameworkの多くのクラスを1つのインターフェイスに登録して解決する方法

public class DependencyRegistrar 
{ 
    public virtual void Register(Autofac_Container builder) 
    { 
      builder.RegisterType<Format_A>().AsSelf().InstancePerLifetimeScope(); 
      builder.RegisterType<Format_B>().AsSelf().InstancePerLifetimeScope(); 
    } 
} 
以下のようautofacのフォーマットタイプ/クラスを登録したIFormatを実装し、インポート

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 
} 

ための独自のロジックを提供しますインポート方法と1つのIFormatインターフェイスを作成しました

インポートアクションを実行すると、現在のフォーマットが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でこれを実現する方法はありますか、同様にクラスの文字列名で型を解決することができます。 私はここを見て、コード

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

答えて

関連する問題