0

We've improved the performance of our API's adding services without state to .SingleInstance() , but I've a question, regarding the demo code attached,

  • The IBusAppService that we are using on the controller is set to SingleInstance(), but inside the BusAppService, we are using more Interfaces, for example ( IBusRepository or IBusDomainService )
  • So the question is, in order to increase the performnace, should we set all interfaces to SingleInstance() inside the IBusAppService or the performance is the same because they are inside a SingleInstance??

I'll attach here some code with the workflow :

The ApiController:

    public class BusApiController : ApiController
    {
        private readonly IBusAppService _iBusAppService;
        private readonly IBusMapper _iBusMapper;
        public BusApiController(IBusAppService iBusAppService,
                                IBusMapper iBusMapper)
        {
            _iBusAppService = iBusAppService;
            _iBusMapper = iBusMapper;
        }

        [HttpGet]
        public BusResponse Get(long id)
        {
            var bus = _iBusAppService.Get(id);

            var busResponse = _iBusMapper.Convert(bus);
            return busResponse;
        }
    }


    public class BusResponse {
       public long Id { get; set; }
    }

    public interface IBusMapper
    {
        BusResponse Convert(Bus bus);
    }

    public class BusMapper : IBusMapper
    {
        public BusResponse Convert(Bus bus)
        {
            if (bus == null) return null;

            var result = new BusResponse{Id = bus.Id};
            return result;
        }
    }

    builder.RegisterType<BusAppService>().As<IBusAppService>().SingleInstance();
    builder.RegisterType<BusMapper>().As<IBusMapper>().SingleInstance(); 

The ApplicationService

public interface IBusAppService
{
    Bus Get(long id);
}

public class BusAppService : IBusAppService
{
    private readonly IBusRepository _iBusRepository;
    private readonly IBusDomainService _iBusDomainService;
    public BusAppService(IBusRepository iBusRepository, IBusDomainService iBusDomainService )
    {
        _iBusRepository = iBusRepository;
        _iBusDomainService = iBusDomainService;
    }
    public Bus Get(long id)
    {
        var bus = this._iBusRepository.Get(id);
        var busTax = this._iBusDomainService.CalculateTax(bus);

        var result = bus;
        return result;
    }
}
user1520494
  • 1,134
  • 2
  • 11
  • 27

1 Answers1

0

Anything consumed by a single instance service will end up being single instance due to captive dependencies. You could change them to be single instance, too, but it won't necessarily change the performance related to instantiation cost that you see now.

Travis Illig
  • 23,195
  • 2
  • 62
  • 85