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

编程入门 行业动态 更新时间:2024-10-22 16:28:56
本文介绍了.NET Core中使用字符串(配置文件)的ServiceCollection配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在核心中的标准 Microsoft.Extensions.DependencyInjection.ServiceCollection 库中配置依赖项注入,而实际上没有引用题? (要从配置文件中获取实现类名称?)

Is there a way to configure dependency injection in the standard Microsoft.Extensions.DependencyInjection.ServiceCollection library in 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配置

本文发布于:2023-11-15 23:52:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1599087.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   配置文件   NET   Core   ServiceCollection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!