Exception thrown when using DI to inject?

  Kiến thức lập trình

Seems a bug with .NETTY or M.E.DI here.

When I pass DefaultChannelHandler through to the constructor (registered as a singleton), I get an exception thrown.

DotNetty.Transport.Channels.ChannelPipelineException: DefaultChannelHandler is not a @Sharable handler, so can’t be added or removed multiple times.

If I new it up inside the class, the issue disappears.

LIke this:

var b = new ServerBootstrap()
    .Group(new MultithreadEventLoopGroup(1), new MultithreadEventLoopGroup())
    .Channel<TcpServerSocketChannel>()
    .ChildOption(ChannelOption.SoRcvbuf, _packetOptions.BufferByteSize)
    .Option(ChannelOption.SoBacklog, 8192)
    .ChildOption(ChannelOption.RcvbufAllocator, new FixedRecvByteBufAllocator(_packetOptions.BufferByteSize))
    .ChildOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
    .ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
    {
        var pipeline = channel.Pipeline;

        if (!string.IsNullOrWhiteSpace(_networkOptions.CertificateFile))
        {
            var certificate = new X509Certificate(_networkOptions.CertificateFile);
            pipeline.AddLast(TlsHandler.Server(certificate));
        }
        
        pipeline.AddLast(new HttpServerCodec());
        pipeline.AddLast(new HttpObjectAggregator(65536));
        pipeline.AddLast(new WebSocketServerProtocolHandler("/", null, true, 65536, false, true));
        pipeline.AddLast(new LengthFieldBasedFrameDecoder(
            65536, 
            0, 
            _packetOptions.FrameLengthByteCount, 
            0, 
            _packetOptions.FrameLengthByteCount));
        pipeline.AddLast(new DefaultChannelHandler(logger2, packetHandler, clientRepository, clientFactory));
    }));

But if I inject it, everything breaks.

I’m registering it as a singleton;
serviceCollection.AddSingleton<DefaultChannelHandler>();

Why is this happening?

New contributor

adam says is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT