2017-06-27 150 views
1

有没有一种方法可以在.net核心中的标准Microsoft.Extensions.DependencyInjection.ServiceCollection库中配置依赖注入,而实际上没有对相关实现类的引用? (从配置文件得到实现类的名字?)在.NET核心中使用字符串(配置文件)的ServiceCollection配置核心

例如:

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

那不是功能内置到开箱DI服务提供商。还有其他的DI框架,它们大部分与ServiceCollectoin集成在一起。所以我建议使用其中之一。 – 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); 
    } 
} 

比方说你有以下服务

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

然后,您可以

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