winform采用Autofac进行依赖注入

一、什么是控制反转、依赖注入?

控制反转(Inversion of Control,IOC)是一种面对对象编程的设计原则,用于降低代码之间的耦合度。其基本思想是借助第三方实现具有依赖关系的对象之间的解耦。

依赖注入(Dependency Injection)是控制翻转(Inversion of Control,IOC)思想的实现方式。依赖注入简化模块的组装过程,降低模块直接的耦合度。

二、使用IOC容器框架Autofac框架

 首先使用nuget安装Autofac。

 

 创建BootStrapper类,用来将项目注入到容器中。

 public static class BootStrapper
    {
        public static IContainer AutoFacContainer;

        public static void BuildContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<Form1>().PropertiesAutowired();//允许属性注入;
            var dalAssemble = Assembly.LoadFrom("Winform.DAL.dll");
            builder.RegisterAssemblyTypes(dalAssemble)
                  .AsImplementedInterfaces()
                  .InstancePerDependency() //默认模式,每次调用,都会重新实例化对象;每次请求都创建一个新的对象;
                  .PropertiesAutowired();//允许属性注入
            var bllAssemble = Assembly.LoadFrom("Winform.BLL.dll");
            builder.RegisterAssemblyTypes(bllAssemble)
                  .AsImplementedInterfaces()
                  .InstancePerDependency()
                  .PropertiesAutowired(); //允许属性注入
            AutoFacContainer = builder.Build();
        }
    }

修改Progarm类

 BootStrapper.BuildContainer();
            using (var scope= BootStrapper.AutoFacContainer.BeginLifetimeScope())
            {
                var form = scope.Resolve<Form1>();
                Application.Run(form);
            }

在Form1使用注入的类

 

 三、代码地址

https://gitee.com/huashao1123/winform-with-autofac

posted @ 2022-09-01 14:02  Defly  阅读(1762)  评论(0编辑  收藏  举报