Monthly Archives: May 2017

Hierarchical Dependency Injection in Angular

DI (Dependency Injection) in Angular 2.0 is hierarchical in nature, for dependency injection to be able to create instances for you, you need to register providers for these classes (or other values) somewhere. and you can configure providers for DI at different levels

  • For the whole application when bootstrapping it. In this cases, all sub injectors (the component ones) will see this provider and share the instance associated with. When interacting, it will be the same instance
  • For a specific component and its sub components. Same as before but for à specific component. Other components won’t see this provider. If you redefine something defined above (when bootstrapping for example), this provider will be used instead. So you can override things. If a provider is registered in one of the child components a new (different) instance is provided for descendants of this component.
  • If a component requests an instance (by a constructor parameter), DI looks “upwards” the component tree (starting from leaf towards the root) and takes the first provider it finds. If an instance for this provider was already created previously, this instance is used, otherwise a new instance is created.

For e.g. In the bbelow sample we have hirerachy of components in this manner

App Component => Parent Component => Child Component => Grand Child component


All the components share a Utility Service which looks some thing like this 

import { Injectable } from '@angular/core';

export class UtilityService {
  public currentDateTime : Date;
  constructor() { 
    console.log("Inside Utility Service Constructor");
    this.currentDateTime = new Date();


As you can see service is not doing any thing special it just has a date time variable which gets initialized when instance of that service is created.

These components are rendered dynamically based on button clicks in following sequence

Click on Show hide it renders the Parent component, in this case parent component is using same instance as that of App Component, it is had not provided its own provider. So the date time which is displayed is same in app and parent component.


Click on show hide of parent component it renders Child Component, not in this case it will display a new date time as we have specified provider of Utility service inside Child Component.


import { Component, OnInit } from '@angular/core';
import { UtilityService } from './../services/utility.service';
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  providers: [UtilityService]
export class ChildComponent implements OnInit {
  public currentDateTime : string;
  constructor(private utilService: UtilityService) {
    this.currentDateTime = this.utilService.currentDateTime.toISOString();

  ngOnInit() {

Now the grand child component is not defining it own provider, so it is using the same instance as that of its ancestor which in this case is child component. So the date time which is displayed in the child component and grand child component is same.

Providers are usually singleton (one instance) objects, that other objects have access to through dependency injection (DI).  Provider is Angular’s term for these reusable objects (dependencies).

Provider lookup – When a component or directive has a dependency (constructor parameter), DI starts looking on this components injector for providers, if it has one it requests the instance from this provider and injects it. If the injector doesn’t have a provider for the requested key (type) then the parent injector is visited, up to the root (bootstrap) until a provider is found and its instance can be injected. (if no provider is found DI throws an error).

We often declare providers in angular this way:

providers: [AnyService]

Which is short cut for representing this

[new Provider(AnyService, {useClass: AnyService})]


Complete source code can be found at Github


ASP.NET Web API and Streaming Video Content

Below post explains how to stream video content through ASP.Net Web API’s, below is the code for Video Controller which inherits from API Controller. API show both GET and POST approaches.

Main thing to concentrate in the code is usage of Push Stream Content. PushStreamContent enables option to send data in small stream packets which then could be used on client side to stream videos, download large files etc.

    /// API Controller for streaming video files.
    public class VideoController : ApiController
        private const string videoFilePath = "~/Movies/";

        /// Gets the live video.
        public IHttpActionResult GetLiveVideo(string videoFileId, string fileName)
            string filePath = Path.Combine(HttpContext.Current.Server.MapPath(videoFilePath), fileName);
            return new VideoFileActionResult(filePath);

        /// Gets the live video using post.
        /// The request.
        public IHttpActionResult GetLiveVideoPost(VideoFileDownloadRequest request)
            string filePath = Path.Combine(HttpContext.Current.Server.MapPath(videoFilePath), request.FileName);
            return new VideoFileActionResult(filePath);

    /// Action Result for Returning Stream
    public class VideoFileActionResult : IHttpActionResult
        private const long BufferLength = 65536;
        public VideoFileActionResult(string videoFilePath)
            this.Filepath = videoFilePath;

        public string Filepath { get; private set; }

        public Task ExecuteAsync(CancellationToken cancellationToken)
            HttpResponseMessage response = new HttpResponseMessage();
            FileInfo fileInfo = new FileInfo(this.Filepath);
            long totalLength = fileInfo.Length;
            response.Content = new PushStreamContent((outputStream, httpContent, transportContext) =>
                    OnStreamConnected(outputStream, httpContent, transportContext);

            response.Content.Headers.ContentLength = totalLength;
            return Task.FromResult(response);

        private async void OnStreamConnected(Stream outputStream, HttpContent content, TransportContext context)
                var buffer = new byte[BufferLength];

                using (var nypdVideo = File.Open(this.Filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    var videoLength = (int)nypdVideo.Length;
                    var videoBytesRead = 1;

                    while (videoLength > 0 && videoBytesRead > 0)
                        videoBytesRead = nypdVideo.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, videoBytesRead);
                        videoLength -= videoBytesRead;
            catch (HttpException ex)
                // Close output stream as we are done


On the client side you can view the video file using below code snippet

<video width="480" height="320" controls="controls" autoplay="autoplay">
        <source src="api/video/live?videoFileId=1001&fileName=sampleVideo.mp4" type="video/mp4">