Skip to content

Instantly share code, notes, and snippets.

@asmorger
Last active November 11, 2016 15:36
Show Gist options
  • Save asmorger/11f232167d4fb57257a2 to your computer and use it in GitHub Desktop.
Save asmorger/11f232167d4fb57257a2 to your computer and use it in GitHub Desktop.
Caliburn.Micro Application Bootstrapper to replace the default DI container with Autofac
<customBootstrapper:CaliburnAutofacApplication
x:Class="MyApplication.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApplication"
xmlns:customBootstrapper="using:MyApplication.CustomBootstrapper">
</customBootstrapper:CaliburnAutofacApplication>
namespace MyApplication.CustomBootstrapper
{
public abstract class CaliburnAutofacApplication : CaliburnApplication
{
protected IContainer Container;
private readonly ContainerBuilder _builder;
private FrameAdapter _rootFrame;
protected CaliburnAutofacApplication()
{
_builder = new ContainerBuilder();
}
protected override void Configure()
{
HandleConfigure(_builder);
Container = _builder.Build();
}
protected override object GetInstance(Type service, string key)
{
object instance;
if (string.IsNullOrEmpty(key))
{
if (Container.TryResolve(service, out instance))
{
return instance;
}
}
else
{
if (Container.TryResolveNamed(key, service, out instance))
{
return instance;
}
}
throw new Exception(string.Format("Could not locate any instances of service {0}.", service.Name));
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
var result = Container.Resolve(typeof(IEnumerable<>).MakeGenericType(service)) as IEnumerable<object>;
return result;
}
protected override void BuildUp(object instance)
{
Container.InjectProperties(instance);
}
protected override void PrepareViewFirst(Windows.UI.Xaml.Controls.Frame rootFrame)
{
_rootFrame = new FrameAdapter(rootFrame);
}
public virtual void HandleConfigure(ContainerBuilder builder)
{
builder.Register(x => _rootFrame).As<INavigationService>().SingleInstance();
/* Register all types by default. This will register the view models. */
builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()).AsSelf().InstancePerDependency();
/* Personal classes to separate & manage the Autofac & Automapper configurations*/
// AutofacConfiguration.Configure(builder);
// AutomapperConfiguration.Configure(Container);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment