.net core Autofac的基本使用

上一篇传送门

.net core IOC(控制反转)、DI(依赖注入) -附项目地址

1.Autofac注册一个类(第三方)

第一步:添加nuget包 : Autofac.Extensions.DependencyInjection并在Startup.cs中添加如下代码

public void ConfigureContainer(ContainerBuilder builder)
{
    builder.RegisterType<TestServiceImpl>(); //RegisterType : 注册一个类
}

第二步:更改Program.cs代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Autofac.Extensions.DependencyInjection;

namespace ioc_demo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            //UseServiceProviderFactory (IServiceProviderFactory<TContainerBuilder>) 重写用于创建应用的服务提供程序的默认工厂。
            Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory()) // 添加autofac 容器
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

第三步:创建AutofacController.cs 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ioc_demo.lmpl;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ioc_demo.Controllers
{
    [Route("api/[controller]")]
    public class AutofacController : Controller
    {
        private TestServiceImpl _service;
        public AutofacController(TestServiceImpl testServiceImpl)
        {
            _service = testServiceImpl;
        }

        [HttpGet]
        public Tuple<int,int> Get()
        {
            int first = _service.Count;
            _service.Add();
            int second = _service.Count;
            return new Tuple<int, int>(first,second);
        }
    }
}

这就实现了第三方Autofac容器注入组件服务,目前代码只注册了组件(类,对象)

2.Autofac将类注册为接口 (第三方)

1.瞬时模式:在Startup.csConfigureContainer中修改为以下代码

public void ConfigureContainer(ContainerBuilder builder)
{
   builder.RegisterType<TestServiceImpl>().As<ITestService>(); //As 将类注册为此接口
}

修改 TestController.cs 中代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ioc_demo.@interface;
using ioc_demo.lmpl;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ioc_demo.Controllers
{
    [Route("api/[controller]")]
    public class TestController : Controller
    {
    //----------------将原来的对象换成现在的接口--------------------
        private ITestService _service;
        public TestController(ITestService testService)
        {
            _service = testService;
        }
    //------------------end------------------------------------
        // GET: api/values
        [HttpGet]
        public Tuple<int,int> Get([FromServices]ITestService service)
        {
            //ITestService testService = new TestServiceImpl(); //接口实现类,程序耦合
            service.Add();
            int first = _service.Count;
            _service.Add();
            int second = _service.Count;
            Console.WriteLine(first); 
            Console.WriteLine(second);
            //如果返回1,2  说明service 与 _service是同一个对象
            return new Tuple<int, int>(first, second);

        }
    }
}

3.Autofac单例模式 (第三方)

使用单例模式:SingleInstance,修改Startup.cs中的ConfigureContainer

public void ConfigureContainer(ContainerBuilder builder)
        {
            //builder.RegisterType<TestServiceImpl>(); //RegisterType 注册一个类
            //builder.RegisterType<TestServiceImpl>().As<ITestService>(); //As 将类注册为此接口;
            builder.RegisterType<TestServiceImpl>().As<ITestService>().SingleInstance();  //单例模式

        }

4.Autofac作用域模式 (第三方)

使用作用域模式:InstancePerLifetimeScope,修改Startup.cs中的ConfigureContainer

public void ConfigureContainer(ContainerBuilder builder)
        {
            //builder.RegisterType<TestServiceImpl>(); //RegisterType 注册一个类
            //builder.RegisterType<TestServiceImpl>().As<ITestService>(); //As 将类注册为此接口;
            //builder.RegisterType<TestServiceImpl>().As<ITestService>().SingleInstance();  //单例模式
            builder.RegisterType<TestServiceImpl>().As<ITestService>().InstancePerLifetimeScope(); //作用域模式
        }

5.Autofac指定构造函数 (第三方)

制定构造函数,我们可以通过UseingConstructor 来指定构造函数来注册,如果不指定构造函数,那么会默认选择最多参数的构造函数

1.新建一个接口 : IConstructor.cs

using System;
namespace ioc_demo.@interface
{
    public interface IConstructor
    {
        public ITestService Service { get; }
    }
}

1.新建一个实现类 : ConstructorImpl.cs

using System;
using ioc_demo.@interface;

namespace ioc_demo.lmpl
{
    public class ConstructorImpl:IConstructor
    {
        public ConstructorImpl()
        {
            Console.WriteLine("我是0个参数的构造函数");
        }

        private ITestService _testService;
        public ConstructorImpl(ITestService testService)
        {
            _testService = testService;
            Console.WriteLine("我是1个参数的构造函数");
        }


        public ITestService Service { get { return _testService; } }
    }
}

3.修改AutofacController.cs 中构造函数如下:

public AutofacController(ITestService testServiceImpl,IConstructor constructor)
        {
            _service = testServiceImpl;
        }

此时访问接口会访问带有一个参数的构造方法

在这里插入图片描述
如果想要访问零个参数的构造函数,需要修改Startup.cs中的注册语句:

public void ConfigureContainer(ContainerBuilder builder)
        {
            //builder.RegisterType<TestServiceImpl>(); //RegisterType 注册一个类
            //builder.RegisterType<TestServiceImpl>().As<ITestService>(); //As 将类注册为此接口;
            //builder.RegisterType<TestServiceImpl>().As<ITestService>().SingleInstance();  //单例模式
            builder.RegisterType<TestServiceImpl>().As<ITestService>().InstancePerLifetimeScope(); //作用域模式


            builder.RegisterType<ConstructorImpl>().As<IConstructor>().UsingConstructor(); //使用零个参数的构造函数
        }

此时我们再次访问接口,就会访问到零个参数的构造函数

在这里插入图片描述

未完待续-----------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

与诸君共勉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值