【Autofac笔记】解决循环依赖
定义类ClassA、ClassB
public class ClassA
{
public ClassA(ClassB b)
{ }
}
public class ClassB
{
public ClassB(ClassA a)
{ }
}
以下代码会抛出循环依赖异常
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ClassA>();
containerBuilder.RegisterType<ClassB>();
var container = containerBuilder.Build();
using (var scope = container.BeginLifetimeScope())
{
var a = scope.Resolve<ClassA>();
var b = scope.Resolve<ClassB>();
}
解决方案
可以使用Lazy,避免抛出循环依赖异常
定义类ClassA、ClassB
public class ClassA
{
public string Name => "A";
private readonly Lazy<ClassB> _b = null;
public ClassA(Lazy<ClassB> b)
{
_b = b;
}
public void Execute()
{
Console.WriteLine(_b.Value.Name);
}
}
public class ClassB
{
public string Name => "B";
private readonly Lazy<ClassA> _a = null;
public ClassB(Lazy<ClassA> a)
{
_a = a;
}
public void Execute()
{
Console.WriteLine(_a.Value.Name);
}
}
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ClassA>();
containerBuilder.RegisterType<ClassB>();
var container = containerBuilder.Build();
using (var scope = container.BeginLifetimeScope())
{
var a = scope.Resolve<ClassA>();
var b = scope.Resolve<ClassB>();
a.Execute();//输出B
b.Execute();//输出A
}
不会抛出异常