ShortBus icon indicating copy to clipboard operation
ShortBus copied to clipboard

AutoFac support

Open brgrz opened this issue 11 years ago • 2 comments

Does it work with Autofac (or any other DI container)? Can it be plugged in?

brgrz avatar Aug 09 '14 11:08 brgrz

There is an ShortBus Autofac Marker NuGet package but I do not know if it'll do what you need.

lruckman avatar Aug 16 '14 01:08 lruckman

@brgrz, there is an Autofac integration package -- see AutofacBasicExample, particularly the container building code (adapted from the AutofacBasicExample.SetUpRootScope method):

var builder = new ContainerBuilder();

// this is needed to allow the Mediator to resolve contravariant handlers (not enabled by default in Autofac)
builder.RegisterSource(new ContravariantRegistrationSource());

// you'll need to make sure to include any assemblies that contain your handlers here
var assembliesToScan = new []{typeof (IMediator).Assembly, GetType().Assembly}

builder.RegisterAssemblyTypes(assembliesToScan)
    .AsClosedTypesOf(typeof (IRequestHandler<,>))
    .AsImplementedInterfaces();

builder.RegisterType<Mediator>().AsImplementedInterfaces().InstancePerLifetimeScope();

// to allow ShortBus to resolve lifetime-scoped dependencies properly, 
// we really can't use the default approach of setting the static (global) dependency resolver, 
// since that resolves instances from the root scope passed into it, rather than 
// the current lifetime scope at the time of resolution.  
// Resolving from the root scope can cause resource leaks, or in the case of components with a 
// specific scope affinity (AutofacWebRequest, for example) it would fail outright, 
// since that scope doesn't exist at the root level.
builder.RegisterType<AutofacDependencyResolver>()
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

var container = builder.Build();

jrnail23 avatar Nov 11 '14 17:11 jrnail23