Skip to content

Instantly share code, notes, and snippets.

@NatMarchand
Created May 4, 2018 12:52
Show Gist options
  • Save NatMarchand/2aa248c2d8c6ac2cda4d5ab86b3413b4 to your computer and use it in GitHub Desktop.
Save NatMarchand/2aa248c2d8c6ac2cda4d5ab86b3413b4 to your computer and use it in GitHub Desktop.
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