How to Use Simple Injector in ASP.NET Core
By FoxLearn 2/3/2025 8:51:15 AM 89
This promotes loose coupling, easier testability, and maintainability. DI also allows for the replacement of implementations without modifying the classes or interfaces that use them.
ASP.NET Core has built-in support for dependency injection, enabling you to inject both framework and application services into your classes rather than relying on tightly coupled components.
Simple Injector is a fast, flexible, and free inversion of control library that integrates well with ASP.NET Core and other .NET platforms. It supports applications like .NET Core, Xamarin, and Mono and is easy to configure with Web API, MVC, WCF, and more.
Step 1: Install Simple Injector NuGet Package
If you have an existing ASP.NET Core MVC project, add the necessary NuGet packages. To do this:
- Right-click the project in Solution Explorer and select "Manage NuGet Packages…".
- In the NuGet Package Manager, search for
SimpleInjector.Integration.AspNetCore.Mvc
and install it.
Alternatively, use the Package Manager Console to install the package:
PM> Install-Package SimpleInjector.Integration.AspNetCore.Mvc
Step 2: Create a Service
Create a class called MessageService
with the following code:
namespace SimpleDemo { public class MessageService : IMessageService { public string GetGreeting() { return "Hello from MessageService!"; } } }
Here’s the interface for MessageService
:
namespace SimpleDemo { public interface IMessageService { string GetGreeting(); } }
Step 3: Configure Simple Injector in ASP.NET Core MVC
Now, set up Simple Injector by adding configuration in the ConfigureServices
method of the Startup
class:
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddSimpleInjector(container, options => { options.AddAspNetCore() .AddControllerActivation(); }); container.Register<IMessageService, MessageService>(Lifestyle.Singleton); }
In this example, IMessageService
is registered with the singleton lifestyle, meaning only one instance of MessageService
will be created during the application's lifetime.
Step 4: Configure the Application Pipeline
In the Configure
method of Startup.cs
, ensure Simple Injector is used in the application pipeline:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSimpleInjector(container); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
Step 5: Update the Index View
Modify the Index.cshtml
view to display the message:
@{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1>@ViewBag.Message</h1> </div>
Step 6: Use Dependency Injection in the Controller
In the HomeController
, use constructor injection to retrieve an instance of IMessageService
:
public class HomeController : Controller { private readonly IMessageService _messageService; public HomeController(IMessageService messageService) { _messageService = messageService; } public IActionResult Index() { ViewBag.Message = _messageService.GetGreeting(); return View(); } }
The GetGreeting()
method of MessageService
will be called, and its result will be displayed on the Index
view.
Step 7: Verify Container Configuration (Optional)
Optionally, you can verify the container configuration to ensure everything is set up correctly. Call Verify()
in the Configure
method:
container.Verify();
This will throw an exception if there are any issues with your configuration.
By integrating Simple Injector with ASP.NET Core, you can take full advantage of dependency injection, enabling a clean, maintainable, and testable architecture. Simple Injector simplifies configuration and reduces the complexities commonly associated with inversion of control libraries.
- Options Pattern In ASP.NET Core
- Implementing Rate Limiting in .NET
- IExceptionFilter in .NET Core
- Repository Pattern in .NET Core
- CRUD with Dapper in ASP.NET Core
- How to Implement Mediator Pattern in .NET
- How to use AutoMapper in ASP.NET Core
- How to fix 'asp-controller and asp-action attributes not working in areas'