简体   繁体   中英

Dependency injection in .Net 5 application using configuration file

I have used Microsoft Unity container for dependency injection with.Net framework where an interface and its required implementation class can be registered and mapped using a configuration file and can be resolved at runtime. Configuration is as shown below,

在此处输入图像描述

I am trying to do the same with.Net5 ASP Core application where it is possible to register programmatically in startup.cs like,

public void ConfigureServices(IServiceCollection services)
{
...
services.AddScoped<IDataProvider,DataProvider>()
}

But couldn't find a way to register it from configuration-file/appsettings.json. Is there any way to achieve this?

I don't think you can do that out of the box. You could write your own logic that loads all contracts and implementations using reflections and register it in container using some custom defined format in your appsettings.json file.

I strongly discourage you to do this because mapping your contracts and implementations in .json file that is not tracked by symbol rename operation will cause your DI container to break anytime you rename one of your services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM