将Ninject更改为Asp MVC的Autofac等效项

时间:2015-08-13 14:49:30

标签: asp.net-mvc ninject autofac

我有下一个代码,我想将其替换为Autofac。 我该怎么办?

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);
 }

}

1 个答案:

答案 0 :(得分:2)

Ninject kernel.Load方法将从程序集中加载实现INinjectModule的所有类。

Autofac 中的等效项是使用RegisterAssemblyModules方法,该方法将加载实现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);

我使用BuildManager.GetReferencedAssemblies()来避免在ASP.net回收过程之后出现问题。有关更多说明,请参阅autofac文档中的IIS Hosted Web Application