Created
May 31, 2014 21:40
-
-
Save dbuksbaum/992b84cd94dcfcd96096 to your computer and use it in GitHub Desktop.
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
using Autofac; | |
using Autofac.Core; | |
using ReactiveUI; | |
using Splat; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
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); | |
resolver.InitializeReactiveUI(); | |
Locator.CurrentMutable = resolver; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment