Last active
September 10, 2017 00:29
-
-
Save italopessoa/5b73d5231ebfcaa2b306fffc883e3e96 to your computer and use it in GitHub Desktop.
Simple boilerplate to configure SimpleInjector in a asp.net core mvc project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using BitcoinShow.Web.Repositories; | |
using BitcoinShow.Web.Repositories.Interface; | |
using BitcoinShow.Web.Services; | |
using BitcoinShow.Web.Services.Interface; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Mvc.Controllers; | |
using Microsoft.AspNetCore.Mvc.ViewComponents; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using SimpleInjector; | |
using SimpleInjector.Integration.AspNetCore.Mvc; | |
using SimpleInjector.Lifestyles; | |
namespace Your.Namespace | |
{ | |
public class Startup | |
{ | |
private Container container = new Container(); | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
IntegrateSimpleInjector(services); | |
} | |
private void IntegrateSimpleInjector(IServiceCollection services) | |
{ | |
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); | |
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); | |
services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(container)); | |
services.AddSingleton<IViewComponentActivator>(new SimpleInjectorViewComponentActivator(container)); | |
services.EnableSimpleInjectorCrossWiring(container); | |
services.UseSimpleInjectorAspNetRequestScoping(container); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
InitializeContainer(app); | |
} | |
private void InitializeContainer(IApplicationBuilder app) | |
{ | |
// Add application presentation components: | |
container.RegisterMvcControllers(app); | |
container.RegisterMvcViewComponents(app); | |
// Add application services. For instance: | |
container.Register<IDependency, Dependency>(Lifestyle.Scoped); | |
container.Verify(); | |
// Cross-wire ASP.NET services (if any). For instance: | |
// container.CrossWire<ILoggerFactory>(app); | |
// NOTE: Do prevent cross-wired instances as much as possible. | |
// See: https://simpleinjector.org/blog/2016/07/ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment