我有下一个代码,我想将其替换为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);
}
}
答案 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。