Web API and Dependency Injeciton

Hello,

Today we will talk about Web API and Unity Dependency Injection Container.

I. Background

Web API is great technology for building RESTful API-s.

For my projects I always use Dependency Injection.

The advantages are many but one of the main for me is that I can efficiently unit test my code and be sure that new changes are not breaking the existing logic.

I think Dependency Injection is must for every project becuase of the wide use of this design pattern, today we have various tools called Dependency Injection Containers.

Dependency Injection Containers simplify the mapping between interfaces and their concrete implementations in the context of Dependency Injections.

They are very handy because take care for initializing instances based on your configuration

II. Unity

For most of my projects I use Unity container. For Web API you can very easily integrate it with just adding this nuget to your project.

And this is fine but it will not work as expected.

You will get strange error for missing parameter less constructor for your controllers. And even if you add one, it will be used by Web API when creating your controllers so none of your dependencies that you pass with constructor will be initialized and you will end up with null reference exceptions later in the action methods.

For simplifying the additional work you need to do, the best approach is too install one more nuget package – Unity bootstrapper for ASP.NET Web API

Unity bootstrapper for ASP.NET Web API will add additional class where you can register mappings between interfaces and concrete implementations and a little bit of configuration that will give you the expected result.

Now your controllers will use the expected constructors and the dependencies will be resolved based on your configuration.

If you are building MVC application there is an alternative package – Unity bootstrapper for ASP.NET MVC

Unity bootstrapper for ASP.NET MVC will make the integration of Unity Container a lot easier with MVC solution.

Have a great day!

Kanio

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s