在MVC 中使用 autofac 实现自动注册

思路很简单:首先我们去找到所有Dll,再去找到实现了IAutoInject 接口的类,然后使用RegisterAssemblyTypes进行注入。IAutoInject是一个空接口,用来辅助我们寻找需要注册的接口

1. 在控制台执行命令安装AutoFac组件

  • Install-Package Autofac

  • Install-Package Autofac.Mvc5 -Version 4.0.2

2. 定义IAutoInject接口

 public interface IAutoInject { }

3. 在Application_Start()中初始化

 protected void Application_Start()
        {
            var builder = new ContainerBuilder();
            //获取IAutoInject的Type
            var baseType = typeof(IAutoInject);
            //获取所有程序集
            var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast().ToArray();
            //自动注册接口
            builder.RegisterAssemblyTypes(assemblies).Where(b => b.GetInterfaces().
            Any(c => c == baseType && b != baseType)).AsImplementedInterfaces(). InstancePerLifetimeScope();
            //自动注册控制器
            builder.RegisterControllers(assemblies);
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

注意: 获取程序集的错误写法(该写法在回收程序池后会导致注册信息丢失): var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToArray();

4. 编写测试代码

  public interface IStudent: IAutoInject
    {
        string Test();
    }
    public class Student : IStudent
    {
        public string Test()
        {
            return "ok";
        }
    }
        public class HomeController : Controller
    {
        private IStudent _student;

        public HomeController(IStudent student)
        {
            _student = student;
        }

        public ActionResult Index()
        {
            return Content(_student.Test());
        }
    }

访问Home/index 即可看到ok成功输出

autofac官网: https://autofac.org/

你可能感兴趣的:(C#,Asp.Net,设计模式)