Skip to content

Channel Scope

Every channel instance creates and uses its own IServiceScope. This means that if you add a scoped service to the DI container and use it in the channel's middleware, you'll have a unique instance per channel. When the channel closes, its service scope is disposed, and all scoped services are disposed accordingly.

public class MyThing
{
    public string Id { get; } = Guid.NewGuid().ToString( "N" );
}

// ...

IServiceCollection services = ; // ...

services.AddScoped<MyThing>();

// ...

/*
For every new channel instance, a new MyThing instance will be created.
This instance is scoped to the lifetime of the channel.
When the channel is closed, the MyThing instance will be disposed along with the channel's service scope.
*/
public class MyAdapter( MyThing thing ) : ChannelAdapter<IReadableByteBuffer>, IInputChannelAdapter
{
    private readonly string id = thing.Id;

    public override Task ExecuteAsync( IAdapterContext context, IReadableByteBuffer data, CancellationToken cancellationToken )
    {
        // ...
    }
}