zoukankan      html  css  js  c++  java
  • Autofac简单学习

    学习地址:https://masuit.com/1192?kw=Autofac

    强烈推荐勤快哥的小站https://masuit.com

    资源多多

    整体代码结构如下:

    一、简单默认方式注入

    1、IService

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace IService
    {
        public interface IUserInfoService
        {
            string[] GetUsers();
        }
    }

    2、Service

    using IService;
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Service
    {
        public class UserInfoService: IUserInfoService
        {
            public string[] GetUsers() {
                return new[] { "张三","李四"};
            }
        }
    }
    

    3、注入

    namespace TestAutoFac
    {
        public class AutofacModuleRegister : Autofac.Module
        {
            protected override void Load(ContainerBuilder builder)
            {
                var basePath = AppContext.BaseDirectory;
                var servicesDllFile = Path.Combine(basePath, "Service.dll");
                var assemblysServices = Assembly.LoadFrom(servicesDllFile);
                //带有接口的带有接口层的服务注入
                builder.RegisterAssemblyTypes(assemblysServices)
                          .AsImplementedInterfaces()
                          .InstancePerDependency();
            }
        }
    }
    

      

    二、属性注入  

    测试了下,跨项目好像不行,只能在同一个项目中测试了一下。

     接口和类实现与上面的代码一致。

    关键点如下:

    1、注入

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    
    namespace TestAutoFac
    {
        public class AutofacModuleRegister : Autofac.Module
        {
            protected override void Load(ContainerBuilder builder)
            {
                            //属性注入
                builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces()
                    .Where(t => t.Name.EndsWith("Controller") || t.Name.EndsWith("UserInfo"))
                    .PropertiesAutowired().AsSelf().InstancePerDependency();
            }
        }
    }
    

    2、组件依赖

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
                services.AddMvc().AddControllersAsServices();//这个加一下
            }
    

      

    更具体的可以见

    https://masuit.com/1435?kw=Autofac

  • 相关阅读:
    常见的分布
    ubuntu16.04获取root权限并用root用户登录
    神经网络与深度学习邱锡鹏学习笔记16多项式回归
    什么是公版显卡,什么是非公版显卡
    高考电子监控揭秘
    买了个2手睡袋
    HTML
    又是一天
    我也想去看珠峰
    Qt 主界面菜单栏和状态栏实现
  • 原文地址:https://www.cnblogs.com/sailing92/p/14155319.html
Copyright © 2011-2022 走看看