Skip to content

Instantly share code, notes, and snippets.

@timReynolds
Created December 4, 2015 11:27
Show Gist options
  • Save timReynolds/97ce921d92b4a6dee5d4 to your computer and use it in GitHub Desktop.
Save timReynolds/97ce921d92b4a6dee5d4 to your computer and use it in GitHub Desktop.
SimpleInjector ASP.NET vNext Setup
public class Startup
{
private Container container = new SimpleInjector.Container();
public Startup(IHostingEnvironment env) {
// ASP.NET default stuff here
}
// This method gets called by the runtime.
public void ConfigureServices(IServiceCollection services) {
// ASP.NET default stuff here
services.AddInstance<IControllerActivator>(
new SimpleInjectorControllerActivator(this.container));
}
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory fac) {
InitializeContainer(app);
RegisterControllers(app);
this.container.Verify();
// Wrap requests in a execution context scope. This allows
// scoped instances to be resolved from the container.
app.Use(async (context, next) => {
using (this.container.BeginExecutionContextScope()) {
await next();
}
});
// ASP.NET default stuff here
}
private void InitializeContainer(IApplicationBuilder app) {
this.container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
// For instance:
container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
}
// In the future, this RegisterControllers method will be moved to an integration package.
private void RegisterControllers(IApplicationBuilder app) {
// Register ASP.NET controllers
var provider = app.ApplicationServices.GetRequiredService<IControllerTypeProvider>();
foreach (TypeInfo type in provider.ControllerTypes) {
var registration = Lifestyle.Transient.CreateRegistration(type, container);
container.AddRegistration(type, registration);
registration.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent,
"ASP.NET disposes controllers.");
}
}
}
internal sealed class SimpleInjectorControllerActivator : IControllerActivator {
private readonly Container container;
public SimpleInjectorControllerActivator(Container container) { this.container = container; }
[DebuggerStepThrough]
public object Create(ActionContext context, Type controllerType) {
return this.container.GetInstance(controllerType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment