Question

While dividing my C# application in layers, I have solved the problem of circular dependency among layers in the following way:

using System;
using System.Collections.Generic;
using System.Text;

using SolvingCircularDependency.Common;
using SolvingCircularDependency.DA;

namespace SolvingCircularDependency.BO
{
    public class MyClass : IPersistent
    {
        private string _message;
        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }

        public bool Save()
        {
             return MyClassDA.Save(this);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace SolvingCircularDependency.Common
{
    public interface IPersistent
    {        
        bool Save();
        string Message { get;}
    }
}

using System;
using System.Collections.Generic;
using System.Text;

using SolvingCircularDependency.Common;

namespace SolvingCircularDependency.DA
{
    public class MyClassDA
    {
        public static bool Save(IPersistent obj)
        {
            Console.WriteLine(obj.Message);

            return true;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;

using SolvingCircularDependency.BO;

namespace SolvingCircularDependency.UI
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myobj = new MyClass();
            myobj.Message = "Goodbye Circular Dependency!";
            myobj.Save();

            Console.ReadLine();
        }
    }
}

Can anyone suggest me any better solution as the "Common" project in the sln is looking redundant to me?

Was it helpful?

Solution

It's up to you to decide if IPersistent should be declared in Common or Service assembly. The best practice (usually) is to declare interfaces in a separate assembly for better layer separation. You need to take into account things like how often developers will create implementations of IPersistent, is it really need to be loose coupled, etc.

OTHER TIPS

Point your attention to Dependency Inversion Principle.

IPersistence is a concern for you DA and a means for your BO to communicate through it. That relationship should end there. Your UI should only know your BO and if you need to define a new interface to support "coding to contracts" define a new one in your BO. Your UI and BO should have separate concerns for what they do within the system.

For example, the IPersistence interface is going to define specific tasks for persisting the record to the database. You don't want that in your UI because it would be bypassing your BO. So unless you want an anemic BO, which really doesn't do anything and shouldn't be there at all, define something new at that level that relates to supporting your business logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top