Skip to content

Instantly share code, notes, and snippets.

@NatMarchand

NatMarchand/Global.asax.cs Secret

Created May 4, 2018
Embed
What would you like to do?
webformdependencyinjection_msdi
using System;
using System.Web;
namespace Microsoft.Extensions.DependencyInjection.WebForms.Sample
{
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
var collection = new ServiceCollection();
collection.AddScoped<IDependency, Dependency>();
var provider = new ServiceProvider(collection.BuildServiceProvider());
HttpRuntime.WebObjectActivator = provider;
}
}
}
using System;
using System.Reflection;
using System.Web;
namespace Microsoft.Extensions.DependencyInjection.WebForms
{
public class ServiceProvider : IServiceProvider
{
private readonly IServiceProvider _serviceProvider;
public ServiceProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public object GetService(Type serviceType)
{
try
{
IServiceScope lifetimeScope;
var currentHttpContext = HttpContext.Current;
if (currentHttpContext != null)
{
lifetimeScope = (IServiceScope)currentHttpContext.Items[typeof(IServiceScope)];
if (lifetimeScope == null)
{
void CleanScope(object sender, EventArgs args)
{
if (sender is HttpApplication application)
{
application.RequestCompleted -= CleanScope;
lifetimeScope.Dispose();
}
}
lifetimeScope = _serviceProvider.CreateScope();
currentHttpContext.Items.Add(typeof(IServiceScope), lifetimeScope);
currentHttpContext.ApplicationInstance.RequestCompleted += CleanScope;
}
}
else
{
lifetimeScope = _serviceProvider.CreateScope();
}
return ActivatorUtilities.GetServiceOrCreateInstance(lifetimeScope.ServiceProvider, serviceType);
}
catch (InvalidOperationException)
{
//No public ctor available, revert to a private/internal one
return Activator.CreateInstance(serviceType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment