使用.NET Core中的字符串(配置文件)进行ServiceCollection配置

有没有办法在.net核心的标准Microsoft.Extensions.DependencyInjection.ServiceCollection库中配置dependency injection,而实际上没有对相关实现类的引用? (从配置文件中获取实现类名?)

例如:

 services.AddTransient("The.Actual.Thing");// Where The.Actual.Thing is a concrete class 

如果您真的热衷于使用字符串参数来动态加载对象,则可以使用创建动态对象的工厂。

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