Dependency Injection in ASP.NET 5

Dependency injection is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle. An injection is the passing of a dependency (a service) to a dependent object (a client). The service is made part of the client’s state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. The pattern is used to create program designs that are loosely coupled and testable.

Types of Dependency Injection

  • Constructor injection: the dependencies are provided through a class constructor. – ASP.NET 5 supports only this.
  • Setter injection: the client exposes a setter method that the injector uses to inject the dependency.
  • Interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

In ASP.NET 5, dependency injection is a first class citizen. While in the previous versions of the framework, DI was partially supported, in ASP.NET 5 it is available throughout the entire stack. A minimalistic DI container is provided out of the box, but you can use your own container (BYOC – Bring Your Own Container support).

The default dependency injection supports following life styles.

Lifestyle Description
Instance A specific instance is given all the time. You are responsible for its initial creation
Transient A new instance is created every time
Singleton A single instance is created and it acts like a singleton
Scoped A single instance is created inside the current scope. It is equivalent to Singleton in the current scope

A popular feature for DI in web applications is to create objects that have a single instance per web request. This means that the objects acts as a singleton inside that request but two distinct requests will have different instances of the objects.

In this post, I am injecting database repository to the controller with scoped life style – runtime will create instance of repository on every web request. Here is the changes required in the Startup.cs.

public void Configure(IApplicationBuilder app)
{
	app.UseErrorPage();
	app.UseServices(services =>
	{
		services.AddMvc();
		services.AddScoped<IUserRepository, UserRepository>();
	});

	app.UseMvc();
}

And in the controller, create a constructor, which accepts IUserRepository parameter, which will be injected by runtime while creating the instance of contolller.

public class HomeController : Controller
{
	private IUserRepository _userRepository;
	public HomeController(IUserRepository userRepository)
	{
		_userRepository = userRepository;
	}
	
	public ActionResult Index()
	{
		return View(_userRepository.Users()); 
	}
}

Here is the IUserRepository interface and its implementation.

public interface IUserRepository
{
	List<User> Users();
}
	
public class UserRepository : IUserRepository
{
	public List<User> Users()
	{
		var listOfUsers = new List<User>();
		for(int i = 0; i< 10; i++)
		{
			listOfUsers.Add(new User(){ Name = "User " + i });
		}
		
		return listOfUsers;
	}
}

public class User
{
	public string Name { get;set; } 
}

You can find more details about Dependency Injection in ASP.NET vNext here

Happy Programming :)

New C# 6.0 features

As part of the Connect(); event, Microsoft introduced VS2015 Preview, which includes C# 6.0 with few more features. (These features are not included in my earlier post What is new in C# 6.0, as I already mentioned these features introduced by Microsoft in the Connect(); event few days back.)

  • nameof operator – nameof operator allows developers to use program elements as text. In MVVM project, you are using property notifications, it is recommended to use strongly typed property notifications, instead of string. Because you are hard coding the property name, if you rename the property, you need to change the string manually. The nameof operator helps you to use the property as the parameter.
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (_firstName != value)
            {
                _firstName = value;
                OnPropertyChanged(nameof(FirstName));
            }
        }
    }
    

    Runtime will replace the property with the property name while generating the IL code.

    IL code generated for nameof operator

    IL code generated for nameof operator

  • null conditional dot operator – as the name indicates it for null checking. This helps you to make null checking fade into the background.
    static void PrintBook(Book book)
    {
        var name = book.Name;
        var price = book.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    I have a function like this, which will print the name and price of the book. Please note I am not doing any null check, if the book instance is null, it will throw exception. The null conditional dot operator helps to avoid this validation and processing. If you are invoking a property of null object instance, it will return null for that property as well, it won’t throw null reference exception.

    static void PrintBook(Book book)
    {
        var name = book?.Name;
        var price = book?.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    In case of value types, Visual Studio will treat the type of the variable as nullable, if you use null conditional dot operator.

    null conditional dot operator - with value types

    null conditional dot operator – with value types

  • string interpolation – Another cool feature, which will help you to manage string formatting easy. In the current framework, you need use string.Format function, it little complex, you need to put numeric place holders ({n}) and based on the number you need to set the variables. String Interpolation will help developers to use actual variables as placeholders.
    var message = string.Format("Book Name :{0} Price :{1}", name, price);
    

    Can be re-write like this.

    var message = "Book Name :\{name} Price :\{price}";
    

    It supports IntelliSense for the variable names, also variables can be identified with different color.

    String Interpolation - IntelliSense

    String Interpolation – IntelliSense

You can download VS 2015 Preview from here

Happy Coding :)

First look into Visual Studio Community 2013

Yesterday Connect(); Event, Scott Guthrie and Soma Somasegar made a number of important announcements for the cloud-first, mobile-first developer. Visual Studio Community 2013 is a new free, fully-featured edition of Visual Studio that lets developers target any platform, from desktop and mobile to web and cloud.

Visual Studio Community 2013

Visual Studio Community 2013

Visual Studio Community 2013 also supports full Visual Studio extensibility, offering access to the ecosystem of over 5000 extensions. You can download it from here. You can also try Visual Studio Community 2013 in Azure VM image.

What is new in Visual Studio Community 2013

  • Professional-grade editing, code analysis, and debugging support – Your favourite Refactor and Debugging features are included.
  • Support for open-source workflows (Git).
  • Compilers for managed languages, C++ and more
  • Cross-platform mobile development including the web, Android, iOS, and Windows Phone with the free Visual Studio Tools for Apache Cordova extension.
  • Take advantage of cloud services with simplified Azure SDK integration, and incorporate modern app analytics and telemetry with Application Insights. Application Insights collects, processes and presents a wide variety of telemetry including performance, usage, availability, exception, crash, environment, log and developer-supplied data from all components of a modern application – including clients (devices and browser), servers, databases and services.
    Application Insights

    Application Insights

  • Access to all the Visual Studio 2013 extensions on the Visual Studio Gallery

Visual Studio Community 2013 includes Update 4, which is a cumulative update of all previous Visual Studio 2013 updates.

Happy Programming :)

What is new in ASP.Net vNext

ASP.Net vNext is the next version of ASP.Net Framework. As part of ASP.NET vNext, the MVC, Web API, and Web Pages frameworks are being merged into one framework, called MVC 6. The new framework removes a lot of overlap between the existing MVC and Web API frameworks.

ASP.Net vNext Features.

  • Side by side support – ASP.NET vNext will support true side by side support, developers can deploy ASP.Net vNext along with web applications, each app can run different versions of .NET vNext side-by-side and upgrade separately, all on the same machine.
  • Lean and Faster – ASP.NET MVC 6 has no dependency on System.Web.dll. ASP.NET vNext is a subset of .Net Framework, which is around 11 MB in size, and it is composed of a collection of NuGet packages.
  • Single Programming model – MVC, Web API, and Web Pages are merged into one framework, called ASP.NET MVC 6. The new framework uses a common set of abstractions for routing, action selection, filters, model binding etc. Dependency injection is built into the framework.
  • Enhanced Developer Experience – vNext uses the Roslyn compiler to compile code dynamically, so developer can edit a code file, refresh the browser, and see the changes without rebuilding the project.
  • Open Source – Microsoft has released entire source code open source via the .NET Foundation. You can see the source at https://github.com/aspnet and follow progress on vNext in real time.

ASP.NET vNext is not backwards compatible with existing ASP.NET applications. However, the current frameworks (Web Forms 5, MVC 5, Web API 2, Web Pages 3, SignalR 2, and Entity Framework 6) will continue to ship in Visual Studio, and will be fully supported in ASP.NET vNext.

Creating Hello World application in ASP.Net vNext

  • Start VS 2014 CTP
  • On the Start Page, click New Project, and then in the New Project dialog, select the C# / Web templates
  • Select the ASP.NET vNext Empty Web Application template, name the project HelloWorld, and click OK.
    New vNext Empty Web Application

    New vNext Empty Web Application

  • One of the vNext feature was it is lean, Microsoft has re-written the Framework and project / solution structure. You will not find the web.config, *.csproj files.
    Solution Explorer with vNext Files

    Solution Explorer with vNext Files

    • Global.json – file helps to support project-to-project references. It also makes it easy to separate test code under a different folder, but still be able to reference application projects from your test projects. This is the Global.json file for empty vNext web application. The “sources” element, indicating the “src” folder is the parent folder for finding project references.
      {
          "sources": [ "src" ]
      }
      
    • Project.json – The project.json file contains a list of dependencies for the project and a list of build output configurations. It can also include a list of commands.
      {
          "dependencies": {
              "Microsoft.AspNet.Server.IIS" : "1.0.0-alpha4"
          },
          "frameworks" : {
              "aspnet50" : { },
              "aspnetcore50" : { }
          }
      }
      

      Dependencies section lists all the dependencies of your application. These are defined by name and version, the runtime loaders will determine what should be loaded. Frameworks section lists target frameworks that will be built, and dependencies that are specific to the configuration. This snippet will build for Desktop (aspnet50) or Core CLR (aspnetcore50). You can find more details about the Project.json schema from github link. Frameworks you can configure using Project property pages, by default application will be using ASP.Net 5.0 Framework. Once you change the Active Target Framework, Visual Studio will update the references appropriately.

      Active Target Framework is ASP.Net

      Active Target Framework is ASP.Net

      Active Target Framework is ASP.Net

      Active Target Framework is ASP.Net Core

      Active Target Framework is ASP.Net Core

      Active Target Framework is ASP.Net Core

    • Startup.cs – By default, the vNext hosting environment expects to find a startup class named Startup. This class must contain a Configure method that takes an IBuilder parameter, and you configure the HTTP pipeline inside this Configure method. The empty project creates the class with nothing in the Configure method. If you were worked in Owin / Katana project, Startup.cs is similar to Owin Startup file. This is the default Startup.cs file for empty vNext application.
      using System;
      using Microsoft.AspNet.Builder;
      
      namespace HelloWorld
      {
          public class Startup
          {
              public void Configure(IApplicationBuilder app)
              {
                  // For more information on how to configure your application, 
                  //visit http://go.microsoft.com/fwlink/?LinkID=398940
              }
          }
      }
      

      To enable MVC in the HTTP pipeline you’ll add a NuGet package and configure the Startup class.

  • In the project.json, you need to add reference of Microsoft.AspNet.Mvc package. The project.json file supports intellisense.
    Intellisense in Project.json for packages

    Intellisense in Project.json for packages

    Intellisense in Project.json for package version as well

    Intellisense in Project.json for package version as well

    "dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-alpha4",
        "Microsoft.AspNet.Mvc": "6.0.0-alpha4"
    }
    

    Once you save the changes, Visual Studio will detect the changes and download the required nuget packages (You can find the details from output window).

  • Now you need to configure the application to use MVC. You can do it by modifying the Startup.cs file, configure() method.
    using Microsoft.AspNet.Builder;
    using Microsoft.Framework.DependencyInjection;
    namespace HelloWorld
    {
        public class Startup
        {
            public void Configure(IApplicationBuilder app)
            {
                app.UseServices(services =>
                {
                    services.AddMvc();
                });
    
                app.UseMvc();
            }
        }
    }
    

    If you didn’t add the using Microsoft.Framework.DependencyInjection, you won’t get services.AddMvc() method. The AddMvc method adds the MVC framework services to the dependency injection system. The UseMvc method configures MVC default settings such as routes.

  • Next create a folder called Controller and add a controller class, HomeController.cs. Also create Home folder inside Views folder, and add a razor view – Index.cshtml. (You won’t get option like Add View by right clicking on Controller method.)
    Solution Explorer - With Controllers and Views

    Solution Explorer – With Controllers and Views

  • Press F5 to start the application. voilà, you have created your first HelloWorld ASP.Net vNext application.

In the next post I will discuss about deployment. Happy Programming :)