2017-01-30 7 views
-1

.Net Core Dependenct Reflectionを使用した注入。私は以下のようなことをすることができますか?.Net Core Startup.cs(サードパーティ製のコンテナなし)依存性注入と反射の併用

エラー:Visual Stuidoデザイナーを表示 ICandidateServiceが指定されたコンテキストでは無効です。

サードパーティ製の容器を使用してください。代わりに

services.AddScoped(ICandidateService)(candidateService); 

書き込みの

public void ConfigureServices(IServiceCollection services) 
      { 
       var candidateService = ServiceInstance.GetService<ICandidateService>(
        new FactoryModel() 
        { 
         Connection = "User ID=postgres;Password=123;Host=localhost;Port=5432;Database=Test12;Pooling=true;", 
         DLLCulture = "Culture=neutral", 
         DLLRef = "EF.Service.SQL", 
         DLLVer = "Version=1.0.0.0", 
         ServiceType = ServiceTypes.PostgreSQL 
        } 
       ); 


       services.AddScoped(ICandidateService)(candidateService); 


    } 


//Service Instance Class 
public static class ServiceInstance 
    { 
     public static T GetService<T>(FactoryModel factoryModel) 
     { 
      if (string.IsNullOrEmpty(factoryModel.Connection) || string.IsNullOrEmpty(factoryModel.DLLRef) || 
       string.IsNullOrEmpty(factoryModel.DLLVer) || string.IsNullOrEmpty(factoryModel.DLLCulture)) 
       throw new NullReferenceException("Missing dataType or connection string"); 

      return GetSQLServiceIntance<T>(factoryModel); 
     } 

     public static T GetSQLServiceIntance<T>(FactoryModel factoryModel) 
     { 
      Type responseContract = GetSQLServiceType<T>(factoryModel); 

      object serviceInstance = Activator.CreateInstance(responseContract, factoryModel.Connection, factoryModel.ServiceType.ToString()); 
      T thisService = (T)serviceInstance; 
      return thisService; 

     } 

     public static Type GetSQLServiceType<T>(FactoryModel factoryModel) 
     { 
      var requestContract = typeof(T).Name.Remove(0, 1); 
      string typeName = $"{factoryModel.DLLRef}.{requestContract}, {factoryModel.DLLRef}, {factoryModel.DLLVer}, {factoryModel.DLLCulture}"; 

      Type responseContract = Type.GetType(typeName); 

      return responseContract; 

     } 
    } 

答えて

0

services.AddSingletone<ICandidateService>(candidateService); 

一つだけ事前に作成されたインスタンスを持つようにしたい場合は、

またはあなたがScopedが必要な場合は、工場出荷時のFuncを作ります寿命:

+0

私はcandidateServiceの下にswiggley reg lineを取得します。エラーはです。引数2:ICandidateServiceから 'System.Func 'に変換できません。 – Sridev

+0

良い、今、具体的なエラーがあります:)今、主な質問は - あなたがScopedサービスを望んでいますか(なぜあなたが登録しているのですか?事前に作成されたインスタンスは常に同じですか?)または 'Singleton'? – Dmitry

+0

実際にはappsettings.jsonからハードコードされたFactoryModel(上記のコード)に応じて、リポジトリの種類に応じて異なるICustomerServiceインスタンスに接続します。はい、あなたは私がシングルトンをやることができると思います。 – Sridev

関連する問題