Autofac依赖注入

Autofac是什么?
Autofac是一种IOC容器,那么什么是IOC容器呢?

先说一下两个概念IOC和DI,我的理解:

  ① IOC:调用者不再创建(不自己new)被调用者的实例,而是交给容器去创建(AutoFac就充当这里的容器),这就是控制反转。

  ② DI:容器创建好的实例再注入调用者的过程,就是依赖注入(比如:属性注入、构造函数注入等)。

控制反转
控制反转背后的核心思想是, 我们不再将类绑定在应用里,让类自己去 "new up" 他们的依赖, 而是反过来在类的构造方法中将依赖传递进去

构建应用

Repository层

 1 public interface IUserRepository
 2     {
 3         List<User> GetModelList(int isEnabled = 1);
 4 
 5     }
 6 
 7  public partial class UserRepository : IUserRepository
 8     {
 9         public List<User> GetModelList(int isEnabled = 1)
10         {
11             var sql = $"select * from [User] where IsEnabled=@IsEnabled ";
12             return DapperHelper.GetModelList<User>(sql, new { IsEnabled = isEnabled });
13         }
14     }

Service层

 1 public interface IUserService : IBaseService<User>
 2     {
 3         List<User> GetModelList(int isEnabled = 1);
 4 
 5     }
 6 
 7 
 8  public partial class UserService : BaseService<User>, IUserService
 9     {
10         private readonly IUserRepository _userRepository;
11 
12         public UserService(IUserRepository userRepository, IBaseRepository<User> baseRepository) : base(baseRepository)
13         {
14             this._userRepository = userRepository;
15         }
16 
17         public List<User> GetModelList(int isEnabled = 1)
18         {
19             return this._userRepository.GetModelList(isEnabled);
20         }
21 
22     }

Web层(注意引用)

 1 public class AutofacConfig
 2     {
 3         /// <summary>
 4         /// 负责调用autofac框架实现业务逻辑层和数据仓储层程序及中的类型对象的创建
 5         /// 负责创建Web控制器类的对象(调用控制器中的有参构造函数),接管DefaultControllerFactory的工作
 6         /// </summary>
 7 
 8         public static void Register()
 9 
10         {
11 
12             // 实例化一个autofac的创建容器
13 
14             var builder = new ContainerBuilder();
15 
16             SetupResolveRules(builder);
17 
18             //注册所有的Controllers
19 
20             builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
21 
22             // 创建一个autofac的容器
23 
24             var container = builder.Build();
25 
26             // 控制器对象由autofac来创建
27 
28             DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
29 
30         }
31 
32 
33 
34         /// <summary>
35         /// 设置配置规则
36         /// </summary>
37         /// <param name="builder"></param>
38 
39         public static void SetupResolveRules(ContainerBuilder builder)
40 
41         {
42             //注册Controller
43 
44             // 告诉autofac框架,将来要创建的控制器类存放在哪个程序集
45             var controllerAssmbly = Assembly.Load("Web");
46             builder.RegisterControllers(controllerAssmbly);
47 
48             //批量注册所有仓储Repository && Service
49             var assemblies = new Assembly[] { Assembly.Load("AutoFac.Repository"), Assembly.Load("AutoFac.Service") }; //声明一个可变数组,可以加载多个类库
50             builder.RegisterAssemblyTypes(assemblies).Where(t => !t.IsAbstract).AsImplementedInterfaces().PropertiesAutowired(); // 获取所有相关类库的程序集
51 
52             //注册泛型仓储
53             builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>));
54             //builder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>));
55 
56             //注册log模块
57             //builder.RegisterModule(new LoggingModule());
58 
59         }
60 
61     }

控制器调用

 1 public class HomeController : Controller
 2     {
 3 
 4         private readonly IUserService _userService;
 5         private readonly IRoleService _roleService;
 6         public HomeController(IUserService userService, IRoleService roleService)
 7         {
 8             _userService = userService;
 9             _roleService = roleService;
10         }
11 
12         public ActionResult Index()
13         {
14             var userModel = _userService.GetModel("085AC7C7-94BE-4A41-93C7-C207939714B9");
15 
16             var userList = _userService.GetModelList();
17 
18             var umodel = _userService.Get("085AC7C7-94BE-4A41-93C7-C207939714B9");
19 
20             var predicateList = new List<IPredicate>();
21             predicateList.Add(Predicates.Field<User>(u => u.IsEnabled, Operator.Eq, 1));
22 
23             var userlist = _userService.GetList(new { IsEnabled = 1 }, new List<ISort>() { new Sort { PropertyName = "CreatTime", Ascending = false } });
24 
25             return View();
26         }
27 
28         public ActionResult About()
29         {
30             ViewBag.Message = "Your application description page.";
31 
32             return View();
33         }
34 
35         public ActionResult Contact()
36         {
37             ViewBag.Message = "Your contact page.";
38 
39             return View();
40         }
41     }

 

 

posted on 2020-06-15 17:03  畅叙趣淘  阅读(264)  评论(0编辑  收藏  举报

导航