【问题标题】:ServiceCollection configuration using strings (config files) in .NET Core在 .NET Core 中使用字符串(配置文件)配置 ServiceCollection
【发布时间】:2017-11-29 23:13:32
【问题描述】:

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

例如:

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

【问题讨论】:

  • 这不是开箱即用的 DI 服务提供商内置的功能。还有其他 DI 框架可以这样做,并且它们中的大多数都与 ServiceCollectoin 集成。所以我建议使用其中之一。

标签: c# .net reflection dependency-injection .net-core


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 2018-10-23
    • 2022-11-11
    • 2019-02-14
    • 2020-07-30
    • 1970-01-01
    • 2020-01-07
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多