Skip to content

Instantly share code, notes, and snippets.

@alexeyzimarev
Created July 22, 2015 13:46
Show Gist options
  • Save alexeyzimarev/4f7e1f0100ef33a5e341 to your computer and use it in GitHub Desktop.
Save alexeyzimarev/4f7e1f0100ef33a5e341 to your computer and use it in GitHub Desktop.
using System;
using Autofac;
using Funq;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using ServiceStack.ServiceInterface;
using ServiceStack.Common;
using ServiceStack.ServiceInterface.Admin;
namespace MyServices.Local.API
{
public class AppHost : AppHostHttpListenerBase
{
private readonly IContainer _container;
public static Assembly[] IncludedAssemblies { get; set; }
public AppHost(IContainer container)
: base("My API", IncludedAssemblies)
{
_container = container;
}
public override void Configure(Container container)
{
LogManager.LogFactory = new SerilogFactory(Log.Logger);
var adapter = new AutofacIocAdapter(_container);
container.Adapter = adapter;
RequestFilters.Add((req, resp, dto) =>
{
var scope = _container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
HostContext.Instance.Items["AutofacScope"] = scope;
});
}
}
}
using Autofac;
using ServiceStack.Common;
using ServiceStack.Configuration;
namespace MyServices.Local.API.Base
{
public class AutofacIocAdapter : IContainerAdapter
{
public IContainer Container { get; private set; }
public AutofacIocAdapter(IContainer container)
{
Container = container;
}
public T Resolve<T>()
{
return !HostContext.Instance.Items.Contains("AutofacScope")
? Container.Resolve<T>()
: ((ILifetimeScope) HostContext.Instance.Items["AutofacScope"]).Resolve<T>();
}
public T TryResolve<T>()
{
T result;
return Container.TryResolve(out result) ? result : default(T);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment