Autofac " Circular component dependency detected " 错误解决

开发环境:ASP.NET Core Web
目标框架:.NET Core 2.2 
   提供者:成长的小猪 Jason Song

错误代码:Autofac.Core.DependencyResolutionException: Circular component dependency detected 
错误场景:使用 Autofac IOC框架  PropertiesAutowired 属性注入,造成此错误代码原因是两种类型互相引用导致,所以我们在用 Autofac 进行属性注入时务必将行为设置为允许循环依赖项。代码如下

    /// 
    /// 用户相关服务
    /// Add by Jason.Song (成长的小猪) on 2019/03/19
    /// 文章来源 http://blog.csdn.net/jasonsong2008
    /// 
    public class UserService
    {
        public OrderService OrderService { get; set; }
    }

    /// 
    /// 订单相关服务
    /// Add by Jason.Song (成长的小猪) on 2019/03/19
    /// 文章来源 http://blog.csdn.net/jasonsong2008
    /// 
    public class OrderService
    {
        public UserService UserService { get; set; }
    }



var builder = new ContainerBuilder();

// 属性注入务必将行为设置为允许循环依赖项 Add by Jason.Song (成长的小猪) on 2019/03/19
// 文章来源 http://blog.csdn.net/jasonsong2008
builder.RegisterType()
    .InstancePerLifetimeScope()
    .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

builder.RegisterType()
    .InstancePerLifetimeScope()
    .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

就是加这个  PropertyWiringOptions.AllowCircularDependencies 就可以解决这个错误哦

 

查看我本人更多原创文章,请点击这里。

你可能感兴趣的:(ASP.NET,ASP.NET,Core,疑难杂症,Circular,component,dependency,Autofac,component,dependency,detected)