Skip to content

Instantly share code, notes, and snippets.

@MuhammadSulaiman001
Last active February 25, 2024 05:43
Show Gist options
  • Save MuhammadSulaiman001/0f74aaa052db101c2b8acb777935c3d3 to your computer and use it in GitHub Desktop.
Save MuhammadSulaiman001/0f74aaa052db101c2b8acb777935c3d3 to your computer and use it in GitHub Desktop.

How Client Consume Service? C#

Approach 1. Pass the service as argument to client methods

  • Abstraction
public interface IService
{
      void DoFavor1();
      void DoFavor2();
}

public interface IClient
{
      void DoSomeMagic1(IService serviceProvider); // implementation will use serviceProvider parameter to call DoFavor* methods
      void DoSomeMagic2(IService serviceProvider); // implementation will use serviceProvider parameter to call DoFavor* methods
}

In this approach, service should be injected into client caller (so client caller can pass it as argument).

Approach 2. Inject the service into client ctor.

  • Abstraction
public interface IService
{
       void DoFavor1();
       void DoFavor2();
}

public interface IClient
{
      void DoSomeMagic1();
      void DoSomeMagic2();
}
  • Concrete
private readonly IService _serviceProvider; // will call DoFavor* methods in DoSomeMagic* implementations

public RealClient(IService serviceProvider)
{
      _serviceProvider = serviceProvider;
}

In this approach, client can use it at any time privately, but, think of a new method at IService (ex. DoFavor3();) which might not be used at all by the client, then how client caller can call DoFavor3();? In this case, the service should be passed to client caller again!!

Approach 3. IClient depends on IService explicily.

  • Abstraction
public interface IService
{
      void DoFavor1();
      void DoFavor2();
}

public interface IClient
{
      IService ServiceProvider { get; }
      void DoSomeMagic1();
      void DoSomeMagic2();
}
  • Concrete
// Usages:
// 1. DoSomeMagic* implementations,
// 2. ANYWHERE OUTSIDE THE CONCRETE, EX: realClient.ServiceProvider.DoFavor1()
public IService ServiceProvider { get; }

public RealClient(IService serviceProvider)
{
      ServiceProvider = serviceProvider;
}

In this approach, client can use the service internally, and client caller can use the service directly. I liked it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment