Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Autofac version of ReactiveUI IMutableDependencyResolver
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Autofac.Core;
namespace ReactiveUI
{
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
{
return string.IsNullOrEmpty(contract)
? _container.Resolve(serviceType)
: _container.ResolveNamed(contract, serviceType);
}
catch (DependencyResolutionException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType, string contract = null)
{
try
{
var enumerableType = typeof (IEnumerable<>).MakeGenericType(serviceType);
object instance = string.IsNullOrEmpty(contract)
? _container.Resolve(enumerableType)
: _container.ResolveNamed(contract, enumerableType);
return ((IEnumerable) instance).Cast<object>();
}
catch (DependencyResolutionException)
{
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);
}
}
// Build a container in your bootstrapper class and call this method to replace RxApp
// internal resolver by Autofac
public static class RxAppAutofacExtension
{
public static void UseAutofacDependencyResolver(IContainer container)
{
var resolver = new AutofacDependencyResolver(container);
RxApp.InitializeCustomResolver((o, type) => resolver.Register(() => o, type));
RxApp.DependencyResolver = resolver;
}
}
}
Owner

alexeyzimarev commented Apr 2, 2014

Can be used by something like this:

        var builder = new ContainerBuilder();
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();
        var container = builder.Build();

        RxAppAutofacExtension.UseAutofacDependencyResolver(container);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment