zoukankan      html  css  js  c++  java
  • .net Core 2.*使用autofac注入

    创建项目

    1.创建一个.net core 项目

    2.创建一个类库

        2.1创建interface文件夹

        2.2创建Service文件夹

    好了给大家看项目目录

    对的。我创建了一个IUserService和一个UserService

    然后给大家贴一下代码

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace AutofaceTest.Service.Interface
    {
        public interface IUserService
        {
            string GetUserName();
        }
    }
    using AutofaceTest.Service.Interface;
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace AutofaceTest.Service.Service
    {
        public class UserService : IUserService
        {
            public string GetUserName()
            {
                return "恩很~是我";
            }
        }
    }

    添加引用

    需要通过nuget添加引用 需要的引用如下

    1.Autofac

    2.Autofac.Configuration

    3.Autofac.Extensions.DependencyInjection

    配置startup文件

    原来的ConfigureServices

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
            }

    修改成这个样子

            public IContainer ApplicationContainer { get; private set; }
            // This method gets called by the runtime. Use this method to add services to the container.
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                //返回的void 修改为 IServiceProvider 这是为了让第三方Ioc容易接管通道 具体在第几层怎么实现我没有深入研究  
                services.AddMvc();
                var builder = new ContainerBuilder();//实例化 AutoFac  容器            
                builder.Populate(services);//管道寄居
                builder.RegisterType<AutofaceTest.Service.Service.UserService>().As<Service.Interface.IUserService>();//UserService注入到IUserService
                ApplicationContainer = builder.Build();//IUserService UserService 构造
                return new AutofacServiceProvider(ApplicationContainer);//将autofac反馈到管道中
            }

    在Controller中调用

            private IUserService _userService;
            public HomeController(IUserService userService)
            {
    
                _userService = userService;
            }
            public IActionResult Index()
            {
                ViewBag.Uname = _userService.GetUserName();//这里就可以直接调用啦。
                return View();
            }

    后记

    刚刚创建了一个.net core的群欢迎大家进入:

    点击链接加入群聊【.Net Core研究团】:https://jq.qq.com/?_wv=1027&k=5IEolkJ

    如果我的文章对您有帮助,希望您可以点个赞。最近打算申请mvp。希望大家帮忙。

  • 相关阅读:
    Linux kernel 之 uart 驱动解析
    按键驱动程序(异步通知)
    常用Linux运维命令
    进程上下文、中断上下文及原子上下文
    Linux 设备驱动开发 —— platform设备驱动应用实例解析
    C++中rapidxml用法及例子(源码)
    hpp.h与.h的区别
    使用Visual Studio扩展插件Visual assist X给代码插入注释模板
    VC++ MFC SDI/MDI Ribbon程序的停靠窗格被关闭后如何再次显示
    “ping某个IP地址,如果ping不通则在dos窗口或弹出MsgBox提示原因”的批处理bat命令
  • 原文地址:https://www.cnblogs.com/Extnet/p/9687172.html
Copyright © 2011-2022 走看看