Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET MVC and ServiceCollection sample
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Microsoft.Extensions.DependencyInjection;
using WebApplication16;
using WebApplication16.Controllers;
[assembly: PreApplicationStartMethod(typeof(MvcApplication), "InitModule")]
namespace WebApplication16
{
public class MvcApplication : System.Web.HttpApplication
{
public static void InitModule()
{
RegisterModule(typeof(ServiceScopeModule));
}
protected void Application_Start()
{
var services = new ServiceCollection();
ConfigureServices(services);
ServiceScopeModule.SetServiceProvider(services.BuildServiceProvider());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DependencyResolver.SetResolver(new ServiceProviderDependencyResolver());
}
private void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ScopedThing>();
services.AddTransient<HomeController>();
}
}
public class ScopedThing : IDisposable
{
public ScopedThing()
{
}
public void Dispose()
{
}
}
internal class ServiceScopeModule : IHttpModule
{
private static ServiceProvider _serviceProvider;
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += Context_BeginRequest;
context.EndRequest += Context_EndRequest;
}
private void Context_EndRequest(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context;
if (context.Items[typeof(IServiceScope)] is IServiceScope scope)
{
scope.Dispose();
}
}
private void Context_BeginRequest(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context;
context.Items[typeof(IServiceScope)] = _serviceProvider.CreateScope();
}
public static void SetServiceProvider(ServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
}
internal class ServiceProviderDependencyResolver : IDependencyResolver
{
public object GetService(Type serviceType)
{
if (HttpContext.Current?.Items[typeof(IServiceScope)] is IServiceScope scope)
{
return scope.ServiceProvider.GetService(serviceType);
}
throw new InvalidOperationException("IServiceScope not provided");
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (HttpContext.Current?.Items[typeof(IServiceScope)] is IServiceScope scope)
{
return scope.ServiceProvider.GetServices(serviceType);
}
throw new InvalidOperationException("IServiceScope not provided");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment