Skip to content

Instantly share code, notes, and snippets.

@cuteribs-1
Last active October 3, 2019 06:28
Show Gist options
  • Save cuteribs-1/dab632704742131c6faf2ce2275a092b to your computer and use it in GitHub Desktop.
Save cuteribs-1/dab632704742131c6faf2ce2275a092b to your computer and use it in GitHub Desktop.

TestService.cs

public class TestService
{
	private int value = 0;

	public int GetValue()
	{
		value++;
		return value;
	}
}

public class ServiceA : TestService { }
public class ServiceB : TestService { }
public class ServiceC : TestService { }

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
	services.AddControllersWithViews();
	services.AddSingleton<ServiceA>();
	services.AddScoped<ServiceB>();
	services.AddTransient<ServiceC>();
}

HomeController.cs

public class HomeController : Controller
{
	private readonly ServiceA serviceA1;
	private readonly ServiceA serviceA2;
	private readonly ServiceB serviceB1;
	private readonly ServiceB serviceB2;
	private readonly ServiceC serviceC1;
	private readonly ServiceC serviceC2;

	public HomeController(ServiceA serviceA1, ServiceA serviceA2, ServiceB serviceB1, ServiceB serviceB2, ServiceC serviceC1, ServiceC serviceC2)
	{
		this.serviceA1 = serviceA1;
		this.serviceA2 = serviceA2;
		this.serviceB1 = serviceB1;
		this.serviceB2 = serviceB2;
		this.serviceC1 = serviceC1;
		this.serviceC2 = serviceC2;
	}

	public IActionResult Index()
	{
		return this.Json(new { 
			A = this.serviceA1.GetValue() + this.serviceA2.GetValue(), 
			B = this.serviceB1.GetValue() + this.serviceB2.GetValue(), 
			C = this.serviceC1.GetValue() + this.serviceC2.GetValue(),
			A1eqA2 = this.serviceA1 == this.serviceA2,
			B1eqB2 = this.serviceB1 == this.serviceB2,
			C1eqC2 = this.serviceC1 == this.serviceC2
		});
	}
}

output

// 1st time
{"a":3,"b":3,"c":2,"a1eqA2":true,"b1eqB2":true,"c1eqC2":false}
// 2nd time
{"a":7,"b":3,"c":2,"a1eqA2":true,"b1eqB2":true,"c1eqC2":false}
// 3rd time
{"a":11,"b":3,"c":2,"a1eqA2":true,"b1eqB2":true,"c1eqC2":false}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment