Thursday, March 3, 2016

Configuring and Resolving Basic Dependency Injection in ASP.NET Core

As you know ASP.NET Core supports Dependency Injection out of box. In this blog, I will show the basic approach to configure and resolve the objects using dependency injection.

The dependency Injection is configured in the Startup along with other services. Here is the code to register our classes for Dependency Injection.

public void ConfigureServices(IServiceCollection services)
{
    //rest of configurations
    services.AddTransient<QuarryDomain>();
    services.AddTransient<QuarryRepository>();
}

In the above code using Transient option, I am creating the object every time I need the object. This option is for lightweight and stateless environments. If you have complicated requirements then you can use the other options such as Scoped, Singleton and Instance.

Once configured the objects can be resolved or passed using constructor injection, as shown below

public class QuarryController : Controller
{
    private QuarryDomain domain;
    public QuarryController(QuarryDomain domain)
    {
        this.domain = domain;
    }
   
    //rest of code
}

In some situations, we may need to manually resolve the objects, for that the framework provides an option to create object as shown below:

AccountDomain accountDomain = HttpContext.RequestServices.GetRequiredService<AccountDomain>();

The above is a basic usage of dependency injection, for more details, please take a look into the asp.net documentation



No comments:

Post a Comment