.NET Core 中使用字符串(配置文件)的 ServiceCollection 配置 [英] ServiceCollection configuration using strings (config files) in .NET Core

查看:35
本文介绍了.NET Core 中使用字符串(配置文件)的 ServiceCollection 配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to configure dependency injection in the standard Microsoft.Extensions.DependencyInjection.ServiceCollection library in .net core, without actually having a reference to the implementation classes in question? (to get implementation class names from configuration files?)

例如:

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

推荐答案

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

If your really keen to use strings parameters to load objects on the fly, you can use a factory that creates dynamic objects.

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

这篇关于.NET Core 中使用字符串(配置文件)的 ServiceCollection 配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆