Search code examples
c#typesmoduleinterfacedependencies

C#: pass an instance of a class from one module to another


I have two modules, that could be present in the target either at the same time together, or on their own. Let's call them ModuleA and ModuleB.

ModuleA has a specific type, which I'd like to use in ModuleB, let's call it SpecificType. However, I'd like to still be able to include ModuleB on it's own (without the ModuleA).

Is it possible to resolve this issue by using interfaces / protocols? What I'm interested is that an object with a specific interface would be passed as a parameter, so it would be impossible to pass e.g. a string.

Example method in ModuleB:

// SpecificType is coming from ModuleA

public void MyMethod(SpecificType myVariableName) {

}

What I might want is something similar to this:

// SpecificType is coming from ModuleA, SpecificTypeInterface from ModuleB
// SpecificType implicitly conforms to SpecificTypeInterface

public void MyMethod(SpecificTypeInterface myVariableName) {

}

Solution

  • If you have some modules who need share interface/type, but you don't want dependence between this modules, you need a other module where is defined interface/type.

    Generaly this other module has the prefix Abstractions, like Microsoft.Extensions.Logging.Abstractions or xunit.abstractions.

    In you case :

    ModuleAbstractions

    public interface ISpecificTypeInterface
    {
        void Foo();
    }
    

    ModuleA

    public class SpecificType : ISpecificTypeInterface
    {
        public void Foo()
        {
            Console.WriteLine("From ModuleA")
        }
    }
    

    ModuleB

    public void MyMethod(ISpecificTypeInterface spe)
    {
        spe.Foo();
    }
    

    ModuleA and ModuleB have the dependence to ModuleAbstractions.