【发布时间】:2016-10-03 20:00:40
【问题描述】:
我正在努力尝试简化应用程序中的一些架构。
我有 3 个项目
- API
- 服务
- 存储库
Api 与服务项目对话,服务与存储库对话。
在我的服务项目中,我需要能够使用其他服务。这将使我减少重复代码的数量
我的代码示例是这样的
public class ApplicationService:IApplicationService
{
private readonly ILog _log;
public IUserService UserService { get; set; }
public ApplicationService(ILog log)
{
_log = log;
if (_log == null)
{
throw new ArgumentNullException("log");
}
if (UserService == null)
{
throw new ArgumentNullException("UserService");
}
}
}
public class UserService:IUserService
{
private readonly IUserRepository _userRepository;
public ICustomerService CustomerService { get; set; }
public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
我的 Autofac 配置的 Startup.cs 看起来像
builder.RegisterType<Services.UserService>().As<IUserService>().InstancePerLifetimeScope().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
builder.RegisterType<Services.ApplicationService>().As<IApplicationService>().InstancePerLifetimeScope().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
builder.RegisterType<Services.CustomerService>().As<ICustomerService>().InstancePerLifetimeScope().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
builder.RegisterAssemblyTypes(Assembly.Load("MyApp.Services"))
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
我确实找到了这个较旧的 SO 帖子 'Autofac Circular Component Dependency Detected' Error,它看起来与我遇到的问题几乎相同。
阅读 autofac 文档我看不出我做错了什么Circular Dependencies
当应用程序当前运行并调用 applicationService 中的构造函数时。 UserService 属性始终为空。为什么会这样?
【问题讨论】:
-
为什么不像
ILog那样通过构造函数注入IUserService? -
我试过了,但遇到了循环问题。阅读文档我的理解是你不能使用构造函数/构造函数注入见autofac.readthedocs.io/en/latest/advanced/…
标签: c# dependency-injection autofac