gpt4 book ai didi

c# - 在 .NET Core 中使用字符串(配置文件)配置 ServiceCollection

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:19 26 4
gpt4 key购买 nike

有没有一种方法可以在 .net core 的标准 Microsoft.Extensions.DependencyInjection.ServiceCollection 库中配置依赖注入(inject),而不需要实际引用相关的实现类? (从配置文件中获取实现类名?)

例如:

services.AddTransient<ISomething>("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<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());
});
}

关于c# - 在 .NET Core 中使用字符串(配置文件)配置 ServiceCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44771138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com