Created
May 18, 2012 00:57
-
-
Save glennblock/2722523 to your computer and use it in GitHub Desktop.
Autofac dependency resolver and scope
This file contains hidden or 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 AutofacApiDependencyResolver : AutofacDependencyScope, IDependencyResolver | |
{ | |
private readonly ILifetimeScope _container; | |
public AutofacApiDependencyResolver(ILifetimeScope container) : base(container) | |
{ | |
_container = container; | |
} | |
public IDependencyScope BeginScope() | |
{ | |
return new AutofacDependencyScope(_container.BeginLifetimeScope()); | |
} | |
} | |
public class AutofacDependencyScope : IDependencyScope | |
{ | |
private ILifetimeScope _container; | |
public AutofacDependencyScope(ILifetimeScope container) | |
{ | |
_container = container; | |
} | |
public IDependencyScope BeginScope() | |
{ | |
throw new NotImplementedException(); | |
} | |
public object GetService(Type serviceType) | |
{ | |
if (_container == null) | |
throw new ObjectDisposedException("this", "This scope has already been disposed"); | |
object instance = null; | |
_container.TryResolve(serviceType, out instance); | |
return instance; | |
} | |
public IEnumerable<object> GetServices(Type serviceType) | |
{ | |
if (_container == null) | |
throw new ObjectDisposedException("this", "This scope has already been disposed"); | |
Type arrayType = typeof (IEnumerable<>).MakeGenericType(serviceType); | |
return (IEnumerable<object>) _container.Resolve(arrayType); | |
} | |
public void Dispose() | |
{ | |
if (_container != null) | |
{ | |
_container.Dispose(); | |
} | |
_container = null; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment