如果你真的热衷于使用字符串参数加载在飞行的物体,你可以使用一个工厂,创建动态对象。
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());
});
}
那不是功能内置到开箱DI服务提供商。还有其他的DI框架,它们大部分与ServiceCollectoin集成在一起。所以我建议使用其中之一。 – Nkosi