Last active
December 12, 2015 05:38
-
-
Save schourode/4722551 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Autofac; | |
using Rebus; | |
using Rebus.Bus; | |
using Rebus.Configuration; | |
namespace Rebus.Autofac | |
{ | |
public class LifetimeScopedAutofacAdapter : IContainerAdapter | |
{ | |
const string ContextKey = "AutofacLifetimeScope"; | |
readonly IContainer _container; | |
public LifetimeScopedAutofacAdapter(IContainer container) | |
{ | |
if (container == null) | |
{ | |
throw new ArgumentNullException("container"); | |
} | |
_container = container; | |
} | |
public IEnumerable<IHandleMessages<T>> GetHandlerInstancesFor<T>() | |
{ | |
var context = MessageContext.GetCurrent(); | |
var lifetimeScope = (ILifetimeScope) context.Items[ContextKey]; | |
return lifetimeScope.Resolve<IEnumerable<IHandleMessages<T>>>().ToArray(); | |
} | |
public void Release(IEnumerable handlerInstances) | |
{ | |
} | |
public void SaveBusInstances(IBus bus) | |
{ | |
var builder = new ContainerBuilder(); | |
builder.RegisterInstance(bus).As<IBus>(); | |
builder.Register(a => MessageContext.GetCurrent()).InstancePerDependency(); | |
builder.Update(_container); | |
bus.Advanced.Events.AddUnitOfWorkManager(new AutofacUnitOfWorkManager(_container)); | |
} | |
class AutofacUnitOfWorkManager : IUnitOfWorkManager | |
{ | |
private readonly IContainer _container; | |
public AutofacUnitOfWorkManager(IContainer container) | |
{ | |
_container = container; | |
} | |
public IUnitOfWork Create() | |
{ | |
var context = MessageContext.GetCurrent(); | |
var lifetimeScope = _container.BeginLifetimeScope(); | |
context.Items.Add(ContextKey, lifetimeScope); | |
return new AutofacUnitOfWork(lifetimeScope); | |
} | |
} | |
class AutofacUnitOfWork : IUnitOfWork | |
{ | |
private readonly ILifetimeScope _lifetimeScope; | |
public AutofacUnitOfWork(ILifetimeScope lifetimeScope) | |
{ | |
_lifetimeScope = lifetimeScope; | |
} | |
public void Commit() | |
{ | |
} | |
public void Abort() | |
{ | |
} | |
public void Dispose() | |
{ | |
_lifetimeScope.Dispose(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment