Skip to content

Instantly share code, notes, and snippets.

@glennblock
Created May 18, 2012 00:57
Show Gist options
  • Save glennblock/2722523 to your computer and use it in GitHub Desktop.
Save glennblock/2722523 to your computer and use it in GitHub Desktop.
Autofac dependency resolver and scope
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