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

时间:2017-06-27 01:43:24

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

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

例如:

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

1 个答案:

答案 0 :(得分:3)

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

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