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

 

转载于:https://www.cnblogs.com/Extnet/p/9687172.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值