ServiceCollection configuration using strings (con

2019-04-16 08:35发布

问题:

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:

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