Skip to content

Commit

Permalink
CM-156 : AddTransient, AddScoped and AddSingleton Services Differences (
Browse files Browse the repository at this point in the history
#8)

* CM-156 : AddTransient, AddScoped and AddSingleton Services Differences
  • Loading branch information
muhammedsalimp authored Nov 23, 2021
1 parent 9262381 commit e084527
Show file tree
Hide file tree
Showing 17 changed files with 350 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31710.8
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DependencyInjectionLifetimeScopes", "DependencyInjectionLifetimeScopes\DependencyInjectionLifetimeScopes.csproj", "{6579A498-D4B5-4C26-950A-E12DF60E6C43}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test", "Test\Test.csproj", "{B5A5DAD7-CD60-4373-9EE6-52736231031F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6579A498-D4B5-4C26-950A-E12DF60E6C43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6579A498-D4B5-4C26-950A-E12DF60E6C43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6579A498-D4B5-4C26-950A-E12DF60E6C43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6579A498-D4B5-4C26-950A-E12DF60E6C43}.Release|Any CPU.Build.0 = Release|Any CPU
{B5A5DAD7-CD60-4373-9EE6-52736231031F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B5A5DAD7-CD60-4373-9EE6-52736231031F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B5A5DAD7-CD60-4373-9EE6-52736231031F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B5A5DAD7-CD60-4373-9EE6-52736231031F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5F52F97B-F40D-4254-8326-5AC894013194}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;

namespace DependencyInjectionLifetimeScopes.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
public readonly ILogger _logger;
public readonly IMyTransientService _myTransientService;
public readonly IMyScopedService _myScopedService;
public readonly IMySingletonService _mySingletonService;

public ValuesController(
IMyTransientService myTransientService,
IMyScopedService myScopedService,
IMySingletonService mySingletonService,
ILogger<ValuesController> logger
)
{
_logger = logger;
_myTransientService = myTransientService ?? throw new ArgumentNullException(nameof(myTransientService));
_myScopedService = myScopedService ?? throw new ArgumentNullException(nameof(myScopedService));
_mySingletonService = mySingletonService ?? throw new ArgumentNullException(nameof(mySingletonService));
}

[HttpGet]
public IActionResult Get()
{
_logger.LogInformation("Transient: " + _myTransientService.InstanceId);
_logger.LogInformation("Scoped: " + _myScopedService.InstanceId);
_logger.LogInformation("Singleton: " + _mySingletonService.InstanceId);

return Ok();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace DependencyInjectionLifetimeScopes
{
public class MyMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public readonly IMySingletonService _mySingletonService;

public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger,
IMySingletonService mySingletonService)
{
_logger = logger;
_mySingletonService = mySingletonService;
_next = next;
}

public async Task InvokeAsync(HttpContext context,
IMyScopedService myScopedService, IMyTransientService myTransientService)
{
_logger.LogInformation("Transient: " + myTransientService.InstanceId);
_logger.LogInformation("Scoped: " + myScopedService.InstanceId);
_logger.LogInformation("Singleton: " + _mySingletonService.InstanceId);

await _next(context);
}
}

public static class MyMiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DependencyInjectionLifetimeScopes
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:31199",
"sslPort": 44346
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"DependencyInjectionLifetimeScopes": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace DependencyInjectionLifetimeScopes
{
public interface IMyScopedService : IMyService
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace DependencyInjectionLifetimeScopes
{
public interface IMyService
{
string InstanceId { get; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace DependencyInjectionLifetimeScopes
{
public interface IMySingletonService : IMyService
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace DependencyInjectionLifetimeScopes
{
public interface IMyTransientService : IMyService
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System;

namespace DependencyInjectionLifetimeScopes
{
public class MyService : IMyTransientService, IMyScopedService, IMySingletonService
{
public string InstanceId { get; } = Guid.NewGuid().ToString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace DependencyInjectionLifetimeScopes
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

services.AddControllers();
services.AddTransient<IMyTransientService, MyService>();
services.AddScoped<IMyScopedService, MyService>();
services.AddSingleton<IMySingletonService, MyService>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "DependencyInjectionLifetimeScopes", Version = "v1" });
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DependencyInjectionLifetimeScopes v1"));
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseMyMiddleware();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using DependencyInjectionLifetimeScopes;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace DependencyInjectionLifetimeScopesTest
{
public class ValuesControllerTest : IClassFixture<CustomWebApplicationFactory<Startup>>
{
private readonly HttpClient _client;

public ValuesControllerTest(CustomWebApplicationFactory<Startup> factory)
{
_client = factory.CreateClient();
}

[Fact]
public async Task WhenInvokingGet_ThenReturnsSuccess()
{
// Get Items
var httpResponse = await _client.GetAsync("/api/values");
httpResponse.EnsureSuccessStatusCode();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using DependencyInjectionLifetimeScopes;
using Microsoft.AspNetCore.Mvc.Testing;

namespace DependencyInjectionLifetimeScopesTest
{
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup>
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.11" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\DependencyInjectionLifetimeScopes\DependencyInjectionLifetimeScopes.csproj" />
</ItemGroup>

</Project>

0 comments on commit e084527

Please sign in to comment.