C
C#14mo ago
CrosRoad95

❔ IServiceProvider, scoped services, scopes

is it correct usage?
projectA:
services.AddScoped<FooContext>();
var serviceProvider = services.BuildServiceProvider()

using(var scope = serviceProvider.CreateScope())
{
var fooContext = serviceProvider.GetRequiredService<FoContext>();
fooContext.SetFoo("foobar");
// let's say here i call mediator, other code that may use foocontext
}

projectB:
public class SomeClass // Part of same service provider, it maybe a mediator request handler
{
public Someclass(FooContext fooContext)
{
var foo = fooContext.GetFoo() // "foobar"
}
}
projectA:
services.AddScoped<FooContext>();
var serviceProvider = services.BuildServiceProvider()

using(var scope = serviceProvider.CreateScope())
{
var fooContext = serviceProvider.GetRequiredService<FoContext>();
fooContext.SetFoo("foobar");
// let's say here i call mediator, other code that may use foocontext
}

projectB:
public class SomeClass // Part of same service provider, it maybe a mediator request handler
{
public Someclass(FooContext fooContext)
{
var foo = fooContext.GetFoo() // "foobar"
}
}
6 Replies
CrosRoad95
CrosRoad95OP14mo ago
FooContext will be initialized onced and then will be reused later inside this scope?
Anu6is
Anu6is14mo ago
you aren't actually using the scope that you created
using(var scope = serviceProvider.CreateScope())
{
//get the service provider from the scope
var fooContext = scope.ServiceProvider.GetRequiredService<FoContext>();
fooContext.SetFoo("foobar");
// let's say here i call mediator, other code that may use foocontext
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
//doing something with this mediator should propogate the current scope
//mediator.Send(...)
}
using(var scope = serviceProvider.CreateScope())
{
//get the service provider from the scope
var fooContext = scope.ServiceProvider.GetRequiredService<FoContext>();
fooContext.SetFoo("foobar");
// let's say here i call mediator, other code that may use foocontext
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
//doing something with this mediator should propogate the current scope
//mediator.Send(...)
}
CrosRoad95
CrosRoad95OP14mo ago
i though this "ServiceProvider" is just reference back and don't need to be used 🤔
Pobiega
Pobiega14mo ago
? Anubis got it right, you need to access the scoped service provider
Exeteres
Exeteres14mo ago
you can create multiple scopes and use them simultaneously so each scope has it's own service provider with services of this scope
Accord
Accord13mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server