.NET依赖注入中解析服务时如何注入运行时参数?
解决方案:运行时动态解析带参数的仓储服务
问题分析
你的JsonPersonRepository依赖动态变化的文件夹路径,无法在启动时通过配置固定注入,需要一种能在运行时传入参数并获取正确实例的方式。
可行方案实现
1. 修正Func注入逻辑(修复原代码问题)
你原本的Func<string, PersonRepository>注入写法存在错误,GetRequiredService无法直接传递构造参数。正确的做法是在Func内部手动创建实例,同时复用DI容器中已注册的其他依赖(IFileSystemProvider、IJsonSerializerWrapper):
services.AddScoped<Func<string, IPersonRepository>>(sp => (folder) => new JsonPersonRepository( folder, sp.GetRequiredService<IFileSystemProvider>(), sp.GetRequiredService<IJsonSerializerWrapper>() ) );
2. 运行时调用方式
在需要仓储的业务类中,注入Func<string, IPersonRepository>,然后根据实时的文件夹路径获取实例:
public class PersonService { private readonly Func<string, IPersonRepository> _personRepoFactory; public PersonService(Func<string, IPersonRepository> personRepoFactory) { _personRepoFactory = personRepoFactory; } public void ProcessPeople(string dynamicFolderPath) { // 根据动态路径生成仓储实例 var repo = _personRepoFactory(dynamicFolderPath); var allPeople = repo.GetAll(); // 执行业务逻辑... } }
3. 可选:封装工厂类(提升代码可读性)
如果需要更复杂的实例创建逻辑,或者想让架构更清晰,可以封装专门的工厂类:
定义工厂接口
public interface IPersonRepositoryFactory { IPersonRepository Create(string folderPath); }
实现工厂类
public class PersonRepositoryFactory : IPersonRepositoryFactory { private readonly IServiceProvider _serviceProvider; public PersonRepositoryFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IPersonRepository Create(string folderPath) { return new JsonPersonRepository( folderPath, _serviceProvider.GetRequiredService<IFileSystemProvider>(), _serviceProvider.GetRequiredService<IJsonSerializerWrapper>() ); } }
注册工厂到DI容器
services.AddScoped<IPersonRepositoryFactory, PersonRepositoryFactory>();
使用工厂类
public class PersonService { private readonly IPersonRepositoryFactory _repoFactory; public PersonService(IPersonRepositoryFactory repoFactory) { _repoFactory = repoFactory; } public void ProcessPeople(string dynamicFolderPath) { var repo = _repoFactory.Create(dynamicFolderPath); // 执行业务逻辑... } }
额外修正提示
你的JsonPersonRepository代码存在两处拼写/逻辑错误,建议修正:
- 构造函数名错误:
JsonTestPlanRepository应改为JsonPersonRepository - 字段赋值错误:
_josnContainerFolder= testPlansFolderPath应改为_josnContainerFolder = josnContainerFolder(建议将josn统一改为json避免拼写混淆)
内容的提问来源于stack exchange,提问作者Hassan Taherian
相关产品推荐
相关产品推荐

