Skip to content

Instantly share code, notes, and snippets.

@StacyGay
Created April 11, 2021 20:34
Show Gist options
  • Save StacyGay/cf6688715f4c95d8414394575c51994b to your computer and use it in GitHub Desktop.
Save StacyGay/cf6688715f4c95d8414394575c51994b to your computer and use it in GitHub Desktop.
Unity DI VNext - UnityServiceProvider
public class UnityServiceScope : IServiceScope
{
private readonly IUnityContainer _container;
public IServiceProvider ServiceProvider { get; }
public UnityServiceScope(IUnityContainer container)
{
_container = container;
ServiceProvider = _container.Resolve<IServiceProvider>();
}
public void Dispose()
{
_container.Dispose();
}
}
public class UnityServiceScopeFactory : IServiceScopeFactory
{
private readonly IUnityContainer _container;
public UnityServiceScopeFactory(IUnityContainer container)
{
_container = container;
}
public IServiceScope CreateScope()
{
return new UnityServiceScope(CreateChildContainer());
}
private IUnityContainer CreateChildContainer()
{
var child = _container.CreateChildContainer();
child.AddExtension(new EnumerableResolutionExtension());
return child;
}
}
public class UnityServiceProvider : IServiceProvider
{
private readonly IUnityContainer _container;
public UnityServiceProvider(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch ()
{
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment