AspNetCore使用Autofac依赖注入

一、安装包    Autofac.Extensions.DependencyInjection

 

 

 二、使用方式

①在Program中,添加对Autofac工厂(AutofacServiceProviderFactory)的服务实现

          .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureContainer<ContainerBuilder>(builder =>
                {
                    builder.RegisterModule<AutofacModule>();
                })

②添加模块类AutofacModule继承Module 重写 Load 方法

public class AutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {

        }
    }

例子:

Autofac区别于AspNetCore默认的依赖注入框架除了性能快还有能够实现属性注册和方法注册:

属性注册Demo:

项目添加两个类库分别为IServices和Services

 

 其中A、B都有GetString() 方法;

现在在AService中实现IBService的属性注册:

public class AService : IAService
    {
        public IBService _bService { get; set; }    
        public string GetString()
        {
            return "AService";
        }
        public string Hey()
        {
            return _bService.GetString();
        }
    }

BService的GetString()为

 

 在Module中进行属性注册

            builder.RegisterType<AService>().As<IAService>().PropertiesAutowired();
            builder.RegisterType<BService>().As<IBService>().SingleInstance();

Controller中使用:

namespace WebApplication1.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestAutofacController : ControllerBase
    {
        private readonly IServiceProvider _serviceProvider;
        public TestAutofacController(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;   
        }
        [HttpGet]
        public IActionResult GetString()
        {
            IAService aService = (IAService)_serviceProvider.GetService(typeof(IAService));
            return Ok(aService.Hey());
        }
    }
}

效果:

 方法注册Demo

在CService中通过方法注册IBService接口并且调用IBService中的方法

 

代码:

public class CService : ICService
    {
        public IBService bService;

        public string GetBService()
        {
            return bService.GetString();
        }

        public string GetString()
        {
            return "CService";
        }

        public void RegisterService(IBService bService)
        {
            this.bService = bService;
        }
    }
            builder.RegisterType<CService>().OnActivated(x=>x.Instance.RegisterService(x.Context.Resolve<IBService>())).As<ICService>().InstancePerDependency();
            builder.RegisterType<BService>().As<IBService>().SingleInstance();

 效果:

 

 

posted @ 2022-09-27 10:43  点终将连成线  阅读(458)  评论(0编辑  收藏  举报