Skip to content

Instantly share code, notes, and snippets.

@jwatney
Created August 8, 2018 22:42
Show Gist options
  • Save jwatney/5a379e0d61d38ca755ffcd8a949d8c80 to your computer and use it in GitHub Desktop.
Save jwatney/5a379e0d61d38ca755ffcd8a949d8c80 to your computer and use it in GitHub Desktop.
WebForms dependency resolution.
public static class DependencyResolution {
public static void ConfigureServices(IContainer container = null, ServiceCollection services = null) {
container = container ?? new Container();
services = services ?? new ServiceCollection();
container.Populate(services);
var provider = container.GetInstance<IServiceProvider>();
HttpRuntime.WebObjectActivator = new HttpRequestScopedServiceProvider(provider);
}
private class HttpRequestScopedServiceProvider : IServiceProvider {
private static readonly BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance;
private readonly IServiceProvider provider;
public HttpRequestScopedServiceProvider(IServiceProvider provider) {
this.provider = provider;
}
public object GetService(Type serviceType) {
var scope = ScopeKeeper.GetScope();
if(scope == null) {
scope = provider.CreateScope();
ScopeKeeper.SetScope(scope);
}
try {
return ActivatorUtilities.GetServiceOrCreateInstance(scope.ServiceProvider, serviceType);
} catch(InvalidOperationException) {
return Activator.CreateInstance(serviceType, Flags, null, null, null);
}
}
private static class ScopeKeeper {
private static HttpContext Context => HttpContext.Current;
public static IServiceScope GetScope() {
return Context?.Items[typeof(IServiceScope)] as IServiceScope;
}
public static void SetScope(IServiceScope scope) {
if(Context != null) {
void DisposeScope(object sender, EventArgs args) {
if(sender is HttpApplication application) {
application.RequestCompleted -= DisposeScope;
scope.Dispose();
}
}
Context.Items.Add(typeof(IServiceScope), scope);
Context.ApplicationInstance.RequestCompleted += DisposeScope;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment