Arbejdsglæde
Arbejdsglæde

Reputation: 14088

Change Ninject to Autofac equivalent for Asp MVC

I have next code and I would like to replace it to Autofac. what should I do ?

public class NinjectKernelFactory
{
  public IKernel Create()
  {
   return LoadAssembliesIntoKernel(new StandardKernel());
  }

  private IKernel LoadAssembliesIntoKernel(IKernel kernel)
  {
    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
     try
     {
       kernel.Load(assembly);
     }
     catch (Exception)
     {
        //Empty Catch used because ninject have problem
        //with loading some of the Sitecore MVC assemblies.
       // Method .ToString()
     }
   }
    return kernel;
  }
}

public class NinjectControllerFactory : DefaultControllerFactory
{

 private IKernel _kernel;
 public NinjectControllerFactory(IKernel kernel)
 {
   _kernel = kernel;
 }

 public override void ReleaseController(IController controller)
 {
   _kernel.Release(controller);
 }

 protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
 {
   return (IController)_kernel.Get(controllerType);
 }

}

Upvotes: 3

Views: 494

Answers (1)

Cyril Durand
Cyril Durand

Reputation: 16192

The kernel.Load method of Ninject will load all class that implement INinjectModule from the assembly.

The equivalent in Autofac is to use the RegisterAssemblyModules method which will load all class that implement IModule.

var builder = new ContainerBuilder();

IEnumerable<Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies();
if (HostingEnvironment.InClientBuildManager)
{
    assemblies = assemblies.Union(BuildManager.GetReferencedAssemblies()
                                              .Cast<Assembly>())
                           .Distinct();
}

builder.RegisterAssemblyModules(assemblies);

I use BuildManager.GetReferencedAssemblies() to avoid issue after ASP.net recycling process. See IIS Hosted Web Application on autofac documentation for more explanation.

Upvotes: 2

Related Questions