解决Castle Windsor的循环依赖

时间:2015-07-29 07:09:07

标签: c# dependency-injection castle-windsor

目前我们在城堡风暴(或可能是任何ioc容器)中遇到循环依赖。我们有:

public class MessageHandler : IMessageHandler
{
    private readonly IService service;

    public MessageHandler(IService service)
    {
        this.service = service;
    }

    private void OnIncommingMessage(string message)
    {
        service.DoWork(message);
    }

    public void SendMessage(string message)
    {
        //sendMessage code
    }
}

public class Service : IService
{
    private readonly IMessageHandler messageHandler;

    public Service(IMessageHandler messageHandler)
    {
        this.messageHandler = messageHandler;
    }

    public void DoWork(string work)
    {
        //Do Work
    }

    private void SomeMethodNeedsToPushData(string message)
    {
        messageHandler.SendMessage(message);
    }

}

public interface IService
{
    void DoWork(string work);
}

public interface IMessageHandler
{
    void SendMessage(string message);
}

在Castle Windsor有解决上述问题的干净方法吗?我不喜欢通过属性注入,因为这两个类都依赖于另一个,所以在我看来这应该总是通过构造函数注入。

1 个答案:

答案 0 :(得分:2)

我认为问题在于你的课程设计。认为你可以通过引入可观察的模式来解决循环依赖。

public interface IService : IDisposable
{
    void Serve(string message);
}

public interface IMessageHandler : IService
{
}

public class MessageHandler : IMessageHandler
{
    private readonly IWorkDispatcher workDispatcher;

    public MessageHandler (IServicesRegistry servicesRegistry)
    {
        servicesRegistry.RegisterService(WorkType.MessageHandler, this);
        this.servicesRegistry = servicesRegistry;
    }
    private void OnIncommingMessage(string message)
    {
        servicesRegistry.SendMessage(WorkType.Service, message);
    }

    public void Serve(string message) // was SendMessage(string message)
    {
        //sendMessage code
    }

    public void Dispose()
    {
        servicesRegistry.RemoveService(this);
    }
}

public interface IWorkerService : IService
{
}

public class WorkerService: IWorkerService 
{
    private readonly IServicesRegistry servicesRegistry

    public Service(IServicesRegistry servicesRegistry)
    {
        servicesRegistry.RegisterService(WorkType.Worker, this);
        this.servicesRegistry = servicesRegistry;
    }

    public void Serve(string message); // was DoWork(string work)
    {
        //Do Work
    }

    private void SomeMethodNeedsToPushData(string message)
    {
        servicesRegistry.SendMessage(WorkType.MessageHandler, message);
    }

    public void Dispose()
    {
        servicesRegistry.RemoveService(this);
    }
}

public enum WorkType
{
    Service,
    MessageHandler
}

public interface IServicesRegistry
{
    void RegisterService(WorkType workType, IService service);
    void RemoveService(IService service);
    void QueueWork(WorkType workType, string message);
}