分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

.net Core 2.*使用autofac注入

发布时间:2023-09-06 02:15责任编辑:赖小花关键词:暂无标签

创建项目

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。希望大家帮忙。

.net Core 2.*使用autofac注入

原文地址:https://www.cnblogs.com/Extnet/p/9687172.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved