2017-04-16 11 views
1

異なるコンストラクタを持つ2つのクラスがあります。
つのパラメータ異なるクラスのインスタンスを異なるコンストラクタで作成する

public TagService(IRepositoryAsync<Tag> tagRespository):base(tagRespository) 
{ 
     _tagRespository = tagRespository; 
} 

がある2つのパラメータがあります。

public AdsService(IRepositoryAsync<Ads> iadsRepository,IUnitOfWork unitOfWork):base(iadsRepository) 
{ 
     this._iadsRepository = iadsRepository; 
     this._unitOfWork = unitOfWork; 
} 

最初はクラスを初期化するために使用しました。

//services have different constractors 
Service = (TEntityService)System.Activator.CreateInstance(
    typeof(TEntityService), 
    new object[] { _repository, _unitOfWork } 
); 

ただし、1つのパラメータでは機能しません。上記のシナリオにはよりよい方法がありますか?コンストラクタ内の異なるパラメータで別のクラスを作成できるメソッドを作成したいと思います。

答えて

1

あなたがAutofacNijectのように、依存性注入(DI)ライブラリを必要とすることサウンド、Simple injectorなど

例えばシンプルインジェクター:

// 1. Create a new Simple Injector container 
container = new Container(); 

// 2. Configure the container (register) 
container.Register<IRepositoryAsync<Tag>, TagService>(); 
container.Register<IRepositoryAsync<Ads>, AdsService>(); 
container.Register<IUnitOfWork >(); 

// 3. Verify your configuration 
container.Verify(); 

//4 
var service = container.GetInstance<TEntityService>(); 
+0

AutofacはXUnit Coreでサポートされていますか?私にシンプルなガイドラインを教えていただけますか?ありがとう –

+0

それは.netコアをサポートしているので、xunitも動作します。これは、次のリンクから始めるのに適しています:http://autofac.readthedocs.io/en/latest/getting-started/index.html – Julian

0

コンストラクタで異なるパラメータで異なるクラスを作成できるメソッドを作成したいと思います。

これを行う最も簡単な方法は、それぞれのケースを確認することです。

public static TEntityService CreateService(object[] constructorParameters) { 
    if (constructorParameters.Length == 1 && 
     constructorParameters[0] is IRepositoryAsync<Tag>) { 
     return (TEntityService)System.Activator.CreateInstance(typeof(TagService), constructorParameters); 
    } else if (constructorParameters.Length == 2 && 
     constructorParameters[0] is IRepositoryAsync<Ads> && 
     constructorParameters[1] is IUnitOfWork) { 
     return (TEntityService)System.Activator.CreateInstance(typeof(AdsService), constructorParameters); 
    } else { 
     return null; // or you can throw an exception 
    } 
} 
関連する問題