Core中使用字符串

Core中使用字符串

本文介绍了.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配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:26