Created
April 11, 2021 20:34
-
-
Save StacyGay/cf6688715f4c95d8414394575c51994b to your computer and use it in GitHub Desktop.
Unity DI VNext - UnityServiceProvider
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 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