CodeDigest.Com Logo
Featured:

Replacing the Inbuilt DI Container with StructureMap in Asp.Net Core MVC

Tagged as: Asp.Net Core Asp.Net Core MVC Posted By

My previous articles, Using In-built Dependency Injection Framework in Asp.Net Core MVC and View Injection, Action Injection and Resolving Framework Services using Asp.Net Core MVC DI Container gave an overview and how to use the inbuilt DI containers to build loosely coupled application with Asp.Net Core. If you are new to Asp.Net Core, I suggest you to read the below articles for getting started in Asp.Net Core framework. 

Start Learning Asp.Net Core - Part 1 - Introduction and Understanding the Basics & Fundamentals

Start Learning Asp.Net Core -Part 2-Understand Project Structure and Startup Class in Visual Studio 2017

Start Learning Asp.Net Core - Part 3 - Creating Deployment Package

Start Learning Asp.Net Core - Part 4 - Deploying and Hosting Asp.Net Core Application

Read Using Autofac Instead of Inbuilt DI Container in Asp.Net Core MVC to use Autofac.

The inbuilt DI container is very light and does not support every feature a full-fledged IOC containers support. As I said in the previous article, Asp.Net Core is designed to replace the inbuilt container with a third party implementation very easily. All the application dependencies and the framework dependencies are added to IServiceCollection in Startup class which acts the inbuilt container. In this article, let’s see how to replace this inbuilt implementation with a third party IOC container called StructureMap.

I will use Visual Studio 2017 Community Edition for demonstration in this article. Visual Studio Community Edition is free for developers, you can download it from here. Assuming you have Visual Studio 2017, we will go ahead and create a simple Asp.Net Core MVC site.

Creating Asp.Net Core Project in Visual Studio 2017

  1. Open Visual Studio 2017. Click New > New Project.

  2. Select .Net Core templates and “Asp.Net Core Web Application (.NET Core)” project type and click OK.

  1. Select a Asp.Net Core project template. I have selected “Web Application” and let the Authentication to No Authentication. Click Ok.

This will create the Asp.Net Core project with all the configuration to start developing Asp.Net Core MVC project.

Including StructureMap Nuget package

Now, let’s include the StrcutureMap Nugect package to replace the inbuilt DI container. To do this, right click the project and click “Manage Nuget Packages..”. In Browse tab, enter “StructureMap.Microsoft.DependencyInjection” as seen below.

Install the package by clicking Install button. Accept any licensing agreements it may ask you during installation.

Next, let’s go ahead and modify the Startup class to use StructureMap IOC container.

Modifying Startup Class

Open Startup.cs class and you see the ConfigureServices() method as seen below.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddDbContext<DBModel>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddTransient<IPostRepository, PostRepository>();
    services.AddTransient<SiteAnalyticsServices>();
}
 

I have added dependencies for DBModel, IPostRepository and SiteAnalyticsServices services into the inbuilt container. To use StructureMap, we need to first change the ConfigureServices() method to return IServiceProvider instead of void and use StructureMap container to take the dependency services.

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddDbContext<DBModel>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    var container = new Container();
    container.Configure(config =>
    {
        config.For<IPostRepository>().Use<PostRepository>();
        config.ForConcreteType<SiteAnalyticsServices>();
        config.Populate(services);
    });
    
    return container.GetInstance<IServiceProvider>();
}
 

Include StructureMap namespace for the above code to work.

The above modified ConfigureServices() now returns IServiceProvider and uses StructureMap container. The config.Populate(services) will copy all the dependencies added into the IServiceCollection into StructureMap container. That’s it. Executing the app, the Asp.Net core will use StructureMap to resolve dependencies.

An alternate approach to map the dependencies to an external class file, the StructureMap allows to define the dependencies in Registry class to keep the ConfigureServices() method clean. To do this, include a class file and name it as RepositoryRegistry and derive it from the Registry base class found in StructureMap namespace. We can map the dependencies in the registry class constructor as seen in the below code.

public class RepositoryRegistry : Registry
{
    public RepositoryRegistry()
    {
        For<IPostRepository>().Use<PostRepository>();
    }
}
 

We can now change the ConfigureServices() method in Startup class to use the above Registry class as seen below.

var container = new Container();
container.Configure(config =>
{
    config.AddRegistry(new RepositoryRegistry());
    config.Populate(services);
});

return container.GetInstance<IServiceProvider>();
 

Thus, we have understood how to replace the inbuilt DI container with StructureMap IOC container in Asp.Net Core applications in this article. Hope you like it!

Happy Coding!!



Feedback

Comments