创建项目
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