mhinze / ShortBus

In-process mediator with low-friction API
MIT License
210 stars 41 forks source link

AutoFac support #33

Open brgrz opened 10 years ago

brgrz commented 10 years ago

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

lruckman commented 10 years ago

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

jrnail23 commented 9 years ago

@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();