使用 C# 和 Autofac 的构造函数注入模式
Constructor Injection pattern using C# and Autofac
我对 DI 模式有点陌生并且遇到了一些问题。
整个故事是这样的:
- 有一个名为 'DataGenerator' 的控制台应用程序负责生成
整个应用程序的样本数据。对 'Autofac' 的引用已添加到该项目。以下是创建国家/地区列表的代码片段:
上述 foreach 循环中出现的异常表示:
{"None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'
on type
'TechnicalTest.Service.AppServices.CountryService' can be invoked with the available services and parameters:\r\nCannot resolve parameter
'TechnicalTest.Repository.EntityRepositories.ICountryRepository countryRepository' of constructor 'Void
.ctor(TechnicalTest.Repository.EntityRepositories.ICountryRepository, TechnicalTest.Repository.UnitOfWork.IUnitOfWork)'."}
- 还有一个项目包括应用程序服务。这是其中之一:
请注意,已添加GenericRepository 和UnitOfWork 项目以介绍每个实体存储库。例如:
我已经在网上搜索异常以及如何解决它,但遗憾的是无法找到适合我的案例的解决方案。我想 CountryService 构造函数或类似的东西一定有问题。
任何帮助或想法将不胜感激。
您是否已DbContext
注册您的容器?从错误消息来看,问题似乎出在解决 CountryRepository
.
的依赖项上
在容器中注册的 类 的所有依赖项都必须在容器中注册。容器如何在没有它需要的所有依赖项的情况下创建 CountryRepository
的实例?
我对 DI 模式有点陌生并且遇到了一些问题。 整个故事是这样的:
- 有一个名为 'DataGenerator' 的控制台应用程序负责生成 整个应用程序的样本数据。对 'Autofac' 的引用已添加到该项目。以下是创建国家/地区列表的代码片段:
上述 foreach 循环中出现的异常表示:
{"None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'TechnicalTest.Service.AppServices.CountryService' can be invoked with the available services and parameters:\r\nCannot resolve parameter 'TechnicalTest.Repository.EntityRepositories.ICountryRepository countryRepository' of constructor 'Void .ctor(TechnicalTest.Repository.EntityRepositories.ICountryRepository, TechnicalTest.Repository.UnitOfWork.IUnitOfWork)'."}
- 还有一个项目包括应用程序服务。这是其中之一:
请注意,已添加GenericRepository 和UnitOfWork 项目以介绍每个实体存储库。例如:
我已经在网上搜索异常以及如何解决它,但遗憾的是无法找到适合我的案例的解决方案。我想 CountryService 构造函数或类似的东西一定有问题。 任何帮助或想法将不胜感激。
您是否已DbContext
注册您的容器?从错误消息来看,问题似乎出在解决 CountryRepository
.
在容器中注册的 类 的所有依赖项都必须在容器中注册。容器如何在没有它需要的所有依赖项的情况下创建 CountryRepository
的实例?