我正在嘗試簡化應用程序中的某些體系結構。爲構造函數/屬性服務層配置autofac依賴關係
我有3個項目
- 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;
}
我Startup.cs爲autofac配置看起來像
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'? –
我試過了,但我遇到了循環問題。閱讀文檔我的理解是你不能使用構造函數/構造函數注入請參閱http://autofac.readthedocs.io/en/latest/advanced/circular-dependencies.html#constructor-constructor-dependencies –