2017-06-27 9 views
1

実際に実装クラスを参照しなくても、.netコアの標準Microsoft.Extensions.DependencyInjection.ServiceCollectionライブラリに依存性注入を設定する方法はありますか? (コンフィギュレーションファイルから実装クラス名を取得するには?).NETコアの文字列(設定ファイル)を使用したServiceCollection設定

例えば:

services.AddTransient<ISomething>("The.Actual.Thing");// Where The.Actual.Thing is a concrete class 
+0

あなたは次のサービス

public interface IClass { string Test(); } public class Class1 : IClass { public string Test() { return "TEST"; } } 

を考えてみましょう。他にもDIフレームワークがあり、そのほとんどがServiceCollectoinと統合されています。だから私はそれらの1つを使用することをお勧めします。 – Nkosi

答えて

3

場でオブジェクトをロードするために、文字列パラメータを使用して、あなたは本当に熱心場合は、動的オブジェクトを作成するファクトリを使用することができます。

public interface IDynamicTypeFactory 
{ 
    object New(string t); 
} 
public class DynamicTypeFactory : IDynamicTypeFactory 
{ 
    object IDynamicTypeFactory.New(string t) 
    { 
     var asm = Assembly.GetEntryAssembly(); 
     var type = asm.GetType(t); 
     return Activator.CreateInstance(type); 
    } 
} 

ボックスDIサービスプロバイダのうちに組み込まれた機能ではないことをあなたができ、その後

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddTransient<IDynamicTypeFactory, DynamicTypeFactory>(); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDynamicTypeFactory dynamicTypeFactory) 
    { 
     loggerFactory.AddConsole(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 

     app.Run(async (context) => 
     { 
      var t = (IClass)dynamicTypeFactory.New("WebApplication1.Class1"); 
      await context.Response.WriteAsync(t.Test()); 
     }); 
    } 
関連する問題