Code · 143 lines · 3464 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143# builder.Services.AddSessionScoped<T>();

A lightweight extension for managing session-scoped data in ASP.NET Core applications.

## Overview

SessionScoped simplifies session management by providing scoped data storage tied to the user's session. It integrates seamlessly with ASP.NET Core's dependency injection, making session-based state management easy and robust.

## Features

- Scoped data tied to the user's session.
- Fully compatible with ASP.NET Core dependency injection.
- Minimal setup required.

## Getting Started

1. **Create a Service implementing IHostedService interface**

```csharp
public class ExampleService(ILoggerFactory loggerFactory) : IHostedService
{
	private readonly ILogger Logger = loggerFactory.CreateLogger<ExampleService>();

	private string name = "unknown";

	public async Task<bool> SetNameAsync(string Name)
	{
		this.name = Name;

		Logger.LogInformation("SetNameAsync {Name}", Name);

		await Task.Delay(100);

		return true;
	}

	public async Task<string> GetNameAsync()
	{
		Logger.LogInformation("GetNameAsync {name}", name);

		await Task.Delay(100);

		return name;
	}

	// IHostedService StartAsync
	public async Task StartAsync(CancellationToken cancellationToken)
	{
		Logger.LogWarning("StartAsync");

		await Task.Delay(100);
	}

	// IHostedService StopAsync
	public async Task StopAsync(CancellationToken cancellationToken)
	{
		Logger.LogWarning("StopAsync");

		await Task.Delay(100);
	}
}
```

2. **Configure AddSessionScoped**

Register the session and `SessionScoped` in your `Startup.cs` or `Program.cs` file:

```csharp
using SessionScopedTest.Services;

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
	ContentRootPath = AppContext.BaseDirectory
});

var services = builder.Services;

services.AddHttpContextAccessor();
services.AddMvc();

services.AddDistributedMemoryCache();
services.AddSession(options =>
{
	options.IdleTimeout = TimeSpan.FromMinutes(20);
	options.Cookie.Name = ".AspNetCore.Session";
	options.Cookie.HttpOnly = true;
	options.Cookie.IsEssential = true;
});

services.AddSessionScoped<ExampleService>();

var app = builder.Build();

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseSession();
app.MapDefaultControllerRoute();

app.Run();
```

3. **Use SessionScopedFactory<T>**

Inject `SessionScopedFactory<ExampleService> factory` into your services or controllers to get the instance of your session-scoped service:

```csharp
public class ExampleController(SessionScopedFactory<ExampleService> factory) : ControllerBase
{
	private readonly ExampleService exampleService = factory.Instance;

	public async Task<IActionResult> Index()
	{
		HttpContext.Session.SetString("Started", DateTime.Now.ToString());

		var result = await exampleService.SetNameAsync($"alphons {Guid.NewGuid()}");

		return Ok("name is set, check url /Example/WhatsYourName");
	}
	public async Task<IActionResult> WhatsYourName()
	{
		var name = await exampleService.GetNameAsync();

		return Ok(name);
	}
}
```

## Requirements

- .NET 8 or higher
- ASP.NET Core

## Contributing

Contributions are welcome! Feel free to fork the repository and submit a pull request.

## License

This project is licensed under the MIT License. See the [LICENSE](https://github.com/alphons/SessionScopedExtension/blob/master/LICENSE) file for details.

---

For more details, visit the [GitHub repository](https://github.com/alphons/SessionScopedExtension/tree/master/SessionScoped).