Created
August 8, 2018 22:42
-
-
Save jwatney/5a379e0d61d38ca755ffcd8a949d8c80 to your computer and use it in GitHub Desktop.
WebForms dependency resolution.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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