ServiceCollection configuration using strings (con

2019-04-16 08:06发布

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?)

For example:

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

1条回答
Explosion°爆炸
2楼-- · 2019-04-16 08:51

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

Lets say you have the following service

public interface IClass
{
    string Test();
}
public class Class1 : IClass
{
    public string Test()
    {
        return "TEST";
    }
}

You can then

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());
        });
    }
查看更多
登录 后发表回答