Skip to content

Instantly share code, notes, and snippets.

@ErikSchierboom
Created June 10, 2019 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErikSchierboom/c0079ab6137b45c1715f84376ee7cbda to your computer and use it in GitHub Desktop.
Save ErikSchierboom/c0079ab6137b45c1715f84376ee7cbda to your computer and use it in GitHub Desktop.
SimpleInjector + ASP.NET Core
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args) =>
CreateWebHostBuilder(args).Build().Run();
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using SimpleInjector;
using WebApplication1.Services;
namespace WebApplication1
{
public class Startup
{
private readonly Container _container = new Container();
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSimpleInjector(_container, options =>
options
.AddAspNetCore()
.AddControllerActivation()
.AddViewComponentActivation()
.AddPageModelActivation()
.AddTagHelperActivation());
services.AddScoped<IUserService, UserService>();
services.AddScoped<ICompanyService, CompanyService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSimpleInjector(_container);
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseHsts();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Services;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ICompanyService _companyService;
public ValuesController(ICompanyService companyService) =>
_companyService = companyService;
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get([FromServices] IUserService userService) =>
_companyService.ListCompanies().Concat(userService.ListUsers()).ToList();
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.HttpsPolicy" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="SimpleInjector.Integration.AspNetCore.Mvc" Version="4.6.0" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment