我不确定如何在以下场景中避免循环引用。由于循环引用,问题是stackoverflow。如何使用Lazy或其他方法解决此问题? 我也不喜欢到处传递容器。
public class MySocket : ISender
{
[Dependency]
public IVehicleManager VehicleManager { get; set; }
public void Connect()
{
Console.WriteLine("MySocket: Connect");
VehicleManager.AddActiveConnection();
}
}
public class MyVehicleManager : IVehicleManager
{
[Dependency]
public ISender Sender { get; set; }
public void AddActiveConnection()
{
Console.WriteLine("MyVehicleManager: Add");
}
public void SendPacketToVehicle(ISender sender)
{
Console.WriteLine("MyVehicleManager: Passing data");
sender.SendPacket();
}
}
static void Main(string[] args)
{
UContainer = new UnityContainer();
UContainer.RegisterType<IVehicleManager, MyVehicleManager>(new ContainerControlledLifetimeManager());
UContainer.RegisterType<MySocket, MySocket>(new ContainerControlledLifetimeManager());
MySocket myInstance = UContainer.Resolve<MySocket>();
}
答案 0 :(得分:0)
Prper方式是创建一个MyVehicleManager和MySocket派生自的超类。或者像你建议的那样懒散,或者做工厂。