首页 > 其他分享 >03_NET6中使用Autofac

03_NET6中使用Autofac

时间:2024-04-13 12:55:24浏览次数:26  
标签:Load 03 Autofac builder student NET6 public schoolboy

安装包:

Autofac

Autofac.Extensions.DependencyInjection

Autofac.Extras.DynamicProxy

中文文档:欢迎来到 Autofac 中文文档! — Autofac 4.0 documentation (autofac-.readthedocs.io)

 

1.新建一个web api项目

新建一个AutofacMamager类,用于注册

 public class AutofacMamager
    {
        public class AutoFacManager : Module
        {
            // 重写 Autofac 管道 Load方法, 在这里注入
            protected override void Load(ContainerBuilder builder)
            {
                /*
                1.瞬态
                 InstancePerDependency();

                2.单例
                SingleInstance();

                3.每个生命周期范围一个实例
                InstancePerLifetimeScope();
                 */

                /*载程序集注册*/
                // 加载程序集 
                Assembly ifirstGrade = Assembly.Load("IModels");
                // 添加程序集依赖
                builder.RegisterAssemblyTypes(ifirstGrade)
                    .Where(t => t.Name.EndsWith("Services"))//对象名后面有Services
                    .AsImplementedInterfaces();//.InstancePerDependency();

                
                Assembly firstGrade = Assembly.Load("Models");
                builder.RegisterAssemblyTypes(firstGrade)
                    .Where(t => t.Name.EndsWith("Services"))//对象名后面有Services
                    .AsImplementedInterfaces();//.InstancePerDependency();


                /*注册具体类*/
                //builder.RegisterType<Student>();
                //builder.RegisterType(typeof(Student));

                /*注册实例*/
                builder.RegisterType<Student>().As<IStudent>();

                base.Load(builder);
            }
        }
    }

 

2.创建一个AutofacExtend类,用于替换

 public static class AutofacExtend
    {
        public static void ReplaceAutofac(this WebApplicationBuilder builder)
        {
            // 替换Autofac
            builder.Host
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureContainer<ContainerBuilder>(build =>
                            {
                                build.RegisterModule(new AutoFacManager());
                            });
        }
    }

 

3.修改Program.cs

            //Autofac
            builder.ReplaceAutofac();
            var app = builder.Build();

 

 

4.创建一个控制器用户测试

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private IStudent _student;
        private ISchoolboyServices _schoolboy;

        public UserController(IStudent student, ISchoolboyServices schoolboy)
        {
            _student=student;
            _schoolboy=schoolboy;
        }

        /// <summary>
        /// 获取学生名称
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetStudentName()
        {
            return _student.GetName();
        }

        /// <summary>
        /// 一年级学生名称
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetSchoolboyName()
        {
            return _schoolboy.Show();
        }
    }

 

标签:Load,03,Autofac,builder,student,NET6,public,schoolboy
From: https://www.cnblogs.com/MingQiu/p/18132714

相关文章

  • F. Alex's whims
    原题链接题解只需要存在两个叶子节点之间距离等于d就好了,于是我们构造一条链,令节点一为滑动变阻器,则根据d改变与节点n的距离即可code#include<bits/stdc++.h>usingnamespacestd;intmain(){intt;cin>>t;while(t--){intn,q;cin>>......
  • 题解:P10320 勇气(Courage)
    P10320勇气(Courage)推导过程本题是一道数学题,重点是如何推导出正确式子。首先,先特判几个特殊点:当\(n>=2\)且\(x=2\)时,是不存在解的,战斗力无论何时都不会超过\(2^{n}\)。当\(x\)不强化就以大于\(2^{n}\)。当\(x\)第一次强化达到\(x^{2}\)时,大于\(2^{n}\)......
  • Qt程序加载Qt platform plugin 'xcb' 出错问题解决
    1.Qt程序运行环境ubuntu16.04Qt5.12.3Qt可执行程序编译后运行Qt可执行程序后出现报错报错内容:qt.qpa.plugin:CouldnotloadtheQtplatformplugin"xcb"in""eventhoughitwasfound.ThisapplicationfailedtostartbecausenoQtplatformplugincouldbe......
  • 解决wpscan运行报错Could not find 'nokogiri' (>= 1.11.4, < 1.13.0) among 125 tota
    报错内容:/usr/lib/ruby/vendor_ruby/rubygems/specification.rb:1404:in`rescueinblockinactivate_dependencies':Couldnotfind'nokogiri'(>=1.11.4,<1.13.0)among125totalgem(s)(Gem::MissingSpecError)Checkedin'GEM_PATH=/roo......
  • [openEuler]使用x2openEuler将CentOS8.2升级openEuler22.03-LTS-SP3提示MultiVersionP
    先上截图: 解决方案:卸载相关rpm包即可,内核卸载可通过#比如我要找到未使用的kernel-core的内核并卸载#动刀内核有无法启动的风险,请自行确认#查看当前内核uname-r#【输出结果】kernel-core-4.18.0-193.28.1.el8_2.x86_64#查看当前安装的kernel-core内核rpm-qkerne......
  • 地铁 2033 重制版全成就攻略
    汉化教程:https://www.bilibili.com/video/BV1J14y1m7Ys/?spm_id_from=333.337.search-card.all.click&vd_source=cab44df4107f3ff939a34437ecc16887全成就:1.Tank(坦克)Kill10Enemiesinarowwithouttakinganydamage.在不受任何伤害的情况下连续杀死10个敌人。2.De......
  • 2024年03月随便做做
    2024.03.01~2024.03.08图论杂题2024.03.13Codeforces-1278F做完了之后翻了翻题解,发现做法都比较复杂,其实有更简单的做法如下。考虑一个关于第二类斯特林数的等式:\[x^k=\sum_{i=0}^{k}S_2(k,i)\cdot{x\choosei}\cdoti!\]因为除开系数之后全是和式,因此可以直接变成期......
  • 题解 P10314【[SHUPC 2024] 函数】
    注意到:\[f(x)=\lfloorx\rfloor,\qquad(x\notin\N)\]代码:intT;doublex;cout<<fixed<<setprecision(12);for(cin>>T;T;--T){cin>>x;cout<<floor(x)<<endl;}感觉说明不够过不了审,于是简单说一下正确性:由诱导公式\(\c......
  • '1' or 'a'='a'
    2222safcscvNQxxl/wJ9vvE2i0XC6wyPUPzA2KO+J+yvnM9IlZDkmeyQO9SXnyy9HkSPOphCeuSG1JUflh0hvT50PADnwCw+7wmaW7LTla18KbasIhuEa4Kx82TuAyQHtatiF01HxLkkCoWuaSa2jy7oIyL0KkZZqfM0ovk+jmlRl786mb5AT7wXCFTnN2yK/Eqo+aCyvkimeWofJJ31+oNXMXLUjcpRH7MXIUqZG4wqDOZ2Lm04LUqA/kEv......
  • 写一个函数,算出两个文件的相对路径,如b='/a/b/12/34/c.php';计算出a的相对路径应该是..
    <?phpfunctionreleative_path($path1,$path2){$arr1=explode("/",dirname($path1));$arr2=explode("/",dirname($path2));for($i=0,$len=count($arr2);$i<$len;$i++){if($arr1[$i]!=......