Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack Funq IoC replacement

In the AppHost class all the method overrides use the Funq container. I use Autofac within my ASP.NET MVC app (I run SS side-by-side with my MVC app).

  1. Is there a way to rather use that Autofac registration from global.asax.cs or is this an overkill to replace?
  2. I commented out this line in AppHost

    //ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));

because it was messing up with my Autofac powered controllers. Is this enough to prevent Autofac and Funq having issues within my app? Or does Funq set itself as a default DependencyResolver anywhere else?

like image 683
mare Avatar asked Sep 08 '12 10:09

mare


1 Answers

Func and AutoFac can work together. With ServiceStack you instruct func to use an AutoFac adapter. This page here tells you how to use different IoC containers. It even provides the code for an AutofacIocAdapter class. https://github.com/ServiceStack/ServiceStack/wiki/The-IoC-container

public class AutofacIocAdapter : IContainerAdapter
{
    private readonly IContainer _container;

    public AutofacIocAdapter(IContainer container)
    {
        _container = container;
    }

    public T Resolve<T>()
    {
        return _container.Resolve<T>();
    }

    public T TryResolve<T>()
    {
        T result;

        if (_container.TryResolve<T>(out result))
        {
            return result;
        }

        return default(T);
    }
}

Then in the AppHost Configure(Container container) method you need to enable this adapter:

//Create Autofac builder
var builder = new ContainerBuilder();
//Now register all depedencies to your custom IoC container
//...

//Register Autofac IoC container adapter, so ServiceStack can use it
IContainerAdapter adapter = new AutofacIocAdapter(builder.Build())
container.Adapter = adapter;
like image 171
kampsj Avatar answered Oct 19 '22 20:10

kampsj