Skip to content

Instantly share code, notes, and snippets.

@jcmm33
Created August 11, 2016 09:43
Show Gist options
  • Save jcmm33/2d0cdfcc71f5509eceaeb49dbb72eb93 to your computer and use it in GitHub Desktop.
Save jcmm33/2d0cdfcc71f5509eceaeb49dbb72eb93 to your computer and use it in GitHub Desktop.
Autofac Mutable Dependancy Resolver
public class AutofacDependencyResolver : IMutableDependencyResolver
{
private readonly IContainer _container;
public AutofacDependencyResolver(IContainer container)
{
_container = container;
}
public void Dispose()
{
}
public object GetService(Type serviceType, string contract = null)
{
try
{
if (string.IsNullOrEmpty(contract))
{
object service;
if (_container.TryResolve(serviceType, out service))
{
return service;
}
return null;
}
else if (_container.IsRegisteredWithName(contract, serviceType))
return _container.ResolveNamed(contract, serviceType);
else if (_container.IsRegistered(serviceType))
return _container.Resolve(serviceType);
else return null;
}
catch (DependencyResolutionException ex)
{
if (ex != null)
{
Debug.WriteLine("AutofaceDependencyResolver:GetService A {0} {1}", serviceType.ToString(),
ex.Message);
}
else
{
Debug.WriteLine("AutofaceDependencyResolver:GetService A {0} ", serviceType.ToString());
}
return null;
}
catch (Exception ex)
{
if (ex != null)
{
Debug.WriteLine("AutofaceDependencyResolver:GetService B {0} {1}", serviceType.ToString(),
ex.Message);
}
else
{
Debug.WriteLine("AutofaceDependencyResolver:GetService B {0} ", serviceType.ToString());
}
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType, string contract = null)
{
try
{
var enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);
var instance = string.IsNullOrEmpty(contract)
? _container.Resolve(enumerableType)
: _container.ResolveNamed(contract, enumerableType);
return ((IEnumerable)instance).Cast<object>();
}
catch (DependencyResolutionException ex)
{
Debug.WriteLine("AutofaceDependencyResolver:GetServices {0} {1}", serviceType.ToString(), ex.Message);
return null;
}
}
public void Register(Func<object> factory, Type serviceType, string contract = null)
{
var builder = new ContainerBuilder();
if (string.IsNullOrEmpty(contract))
{
builder.Register(x => factory()).As(serviceType).AsImplementedInterfaces();
}
else
{
builder.Register(x => factory()).Named(contract, serviceType).AsImplementedInterfaces();
}
builder.Update(_container,ContainerBuildOptions.IgnoreStartableComponents);
}
public IDisposable ServiceRegistrationCallback(Type serviceType, string contract, Action<IDisposable> callback)
{
throw new NotImplementedException();
}
}
public static class RxAppAutofacExtension
{
public static void UseAutofacDependencyResolver(IContainer container)
{
var resolver = new AutofacDependencyResolver(container);
Locator.CurrentMutable = resolver;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment