自定义AutofacControllerFactory工厂类来替换掉DefaultControllerFactory,来实现依赖注入。

参考文档:https://autofaccn.readthedocs.io/zh/latest/integration/mvc.html?highlight=registercontrollers

注意关键点:

1、在MVC项目中,找到Global.asax文件,在Application_Start中替换掉默认的工厂
2、自己写的工厂要继承DefaultControllerFactory类,并重新GetControllerInstance方法,将原有的创建controll的方法替换掉。
3、Autofac需要引用两个nuget包,分别是Autofac和Autofac.Mvc5。

不废话,直接看源码(后面附为什么使用ControllerBuilder来设置Factory,使用ILSpy来查看源码)

protected void Application_Start()
{
    //.............................
   	//.............................
    //重要的一步,用自己写的工厂,替换掉原默认的工厂
    //为什么这样写呢?你需要看System.Web.Mvc.dll的源码,在看mvchandler里面的ProcessRequest方法,
    ControllerBuilder.Current.SetControllerFactory(typeof(AutofacControllerFactory));
}



public class AutofacControllerFactory : DefaultControllerFactory
{
  protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
  {
      //return base.GetControllerInstance(requestContext, controllerType);
      //替换掉原有注册controller的工厂
      return (IController)AutofacContainerBuiler.container.Resolve(controllerType);
  }

}
public class AutofacContainerBuiler
{
    public static IContainer container = null;
    static AutofacContainerBuiler()
    {
        Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();

        // Register your MVC controllers. (MvcApplication is the name of
        // the class in Global.asax.)
        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        //// OPTIONAL: Register model binders that require DI.
        //builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
        //builder.RegisterModelBinderProvider();

        //// OPTIONAL: Register web abstractions like HttpContextBase.
        //builder.RegisterModule<AutofacWebTypesModule>();

        //// OPTIONAL: Enable property injection in view pages.
        //builder.RegisterSource(new ViewRegistrationSource());

        //// OPTIONAL: Enable property injection into action filters.
        //builder.RegisterFilterProvider();


        builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope();


        container = builder.Build();

    }
}

public interface IService
{
    string Show();
}
public class Service : IService
{
    public string Show()
    {
        return "wangshiqiao";
    }
}
第一张图

第二张图

第三张图

posted @ 2020-07-23 12:43  hg000  阅读(309)  评论(0)    收藏  举报