-2

I have 5 projects in a solution. A and B are two projects. B is already referencing A. Now I want to call methods in A from B. But the problem is circular dependency. I saw it being solved by using Events. I tried this:

A------->B(reference A)
B------->A(dependency)

I also tried it from A using events. But I can't add listener methods to the event because listener methods are in B. I cannot have any access to B.

Can anyone tell me how this problem can be solved using events. I don't have much experience in events, delegates. Please correct me if I am wrong.

jsanalytics
  • 13,058
  • 4
  • 22
  • 43
bibin
  • 5
  • 3
  • [Click](https://stackoverflow.com/q/4586334/1997232). – Sinatr Nov 08 '17 at 11:28
  • 3
    The simple answer is rethink your solution. If you set up your solution in the right way, this does not happen. It may not be the answer you like, but I strongly suggest spending some time at the drawing board and considerations of refactoring. – oerkelens Nov 08 '17 at 11:31
  • Move all code needed by A and B to another common lib C. – BWA Nov 08 '17 at 11:36
  • 2
    Why are A and B separate projects in the first place? Apparently they cannot be shipped separately. – Eric Lippert Nov 08 '17 at 14:37
  • Taken literally, the marked duplicate will solve your problem. But, heed the other advice given here. First, if the two assemblies are mutually required, why aren't they just a single assembly? Second, if they really should be separate, that suggests it's _wrong_ for at least one of the assemblies to know types in the other. In that case, more likely you should be using inversion-of-control or some similar technique (often involving subscribing to events, passing in delegates, etc.) so that the one assembly doesn't need to know types in the other. – Peter Duniho Nov 09 '17 at 03:33

1 Answers1

0

On way to solve this is to have a Common project which bridge the gap between your projects. If you, for example, want to share a Lexicon of translations between your projects, you could add something like this to your Common project:

// Leaving out locking and error handling
public static Lexicon
{
    private static Func<string, string> _lookup=null;
    public static void Initialize(Func<string, string> lookup)
    {
        _lookup=lookup;
    }
    public static string Translate(string key)
    {
        return _lookup(key);
    }
}

If project A actually contains the translation dictionary, it could initialize the lexicon like this:

Lexicon.Initialize(key => dictionary[key]);

Both projects can use the Lexicon

K Ekegren
  • 218
  • 1
  • 6