This post will be short and sweet, albeit one that caused me a bit of a headache. I recently worked on an ASP.NET Core project and I wanted to take advantage of the built-in Dependency Injection service to inject various services to the controllers. However, one of the services required a parameter in the constructor. This is not highly unusual so I was expecting to quickly find an example in the official docs, explaining how to do this. My search, however, returned no results. I then turned to Google/Bing but guess what? Nothing. Every example I found re-iterated the examples shown in the official documentation.
At this point, I had 2 options:
- Option 1: Bring in a 3rd party IoC library which is fully supported by ASP.NET Core (e.g. Ninject)
- Option 2: Continue my search for a possible solution with what ASP.NET core has to offer
I decided to go with option 2 thinking that I could go back to option 1 once I exhausted all my technical sources. Luckily, Twitter came to the rescue and Kristian Hellang provided a sweet and short answer to my problem. The solution was simple, eloquent and made total sense, yet it was nowhere documented!
To be able to use the provided Dependency Injection we need to add the appropriate NuGet package. This comes in the form of
Microsoft.Extensions.DependencyInjection. You could download it using the NuGet Gui
Or, you could added using the NuGet command line or edit the
*.csproj file directly, since this is perfectly acceptable in the .NET Core era.
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="1.1.1" />
With the right references in place, you can now implement the DI code necessary for your application. The following code shows you how to configure DI for objects that have parameters in the constructor.
The important bit here is in this line:
services.AddTransient<IMyService>(s => new MyService("MyConnectionString"));
The official .NET Core docs still lack a good example around this so for this post will have to do. Who knows, I may manage to get this change pushed up and published alongside simpler examples in the ASP.NET docs? In the meantime, I hope I managed to save you some headaches.
Big thanks to [Kristian Hellang](https://twitter.com/khellang" target="_blank) and [Jonathan Channon](https://twitter.com/jchannon" target="_blank), both of which came to the rescue and took time off their busy schedule to provide solid, working examples. Community crowdsourcing FTW!