【问题标题】:Configure autofac dependencies for constructor/property service layer为构造函数/属性服务层配置 autofac 依赖项
【发布时间】: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


【解决方案1】:

在 ApplicationService 构造函数执行中,UserService 将始终为 null,因为您没有在构造函数中为其分配任何内容(您没有使用构造函数注入)。所以这段代码总会抛出异常:

if (UserService == null)
{
     throw new ArgumentNullException("UserService");
}

删除此代码,您应该没问题。 DI容器中的属性注入在使用构造函数创建对象后将依赖项分配给对象属性(没有其他方法)。

顺便说一句,我在您包含的代码中看不到任何循环依赖。您还没有包含 ICustomerService 和 IUserRepository 实现的代码,所以可能有一些东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    相关资源
    最近更新 更多