开发环境:ASP.NET Core Web
目标框架:.NET Core 2.2
提供者:成长的小猪 Jason Song
错误代码:Autofac.Core.DependencyResolutionException: Circular component dependency detected
错误场景:使用 Autofac IOC框架 PropertiesAutowired
属性注入,造成此错误代码原因是两种类型互相引用导致,所以我们在用 Autofac 进行属性注入时务必将行为设置为允许循环依赖项。代码如下
/// <summary>
/// 用户相关服务
/// Add by Jason.Song (成长的小猪) on 2019/03/19
/// 文章来源 http://blog.youkuaiyun.com/jasonsong2008
/// </summary>
public class UserService
{
public OrderService OrderService { get; set; }
}
/// <summary>
/// 订单相关服务
/// Add by Jason.Song (成长的小猪) on 2019/03/19
/// 文章来源 http://blog.youkuaiyun.com/jasonsong2008
/// </summary>
public class OrderService
{
public UserService UserService { get; set; }
}
var builder = new ContainerBuilder();
// 属性注入务必将行为设置为允许循环依赖项 Add by Jason.Song (成长的小猪) on 2019/03/19
// 文章来源 http://blog.youkuaiyun.com/jasonsong2008
builder.RegisterType<UserService>()
.InstancePerLifetimeScope()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
builder.RegisterType<OrderService>()
.InstancePerLifetimeScope()
.PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
就是加这个 PropertyWiringOptions.AllowCircularDependencies 就可以解决这个错误哦