Autofac之控制器属性注入

Autofac之控制器属性注入

前面一节介绍了Autofac整合到WebAPI,这节介绍Autofac之控制器属性注入。

环境

Win10+VS2020+.NET 5.0 +Autofac 6.3.0

 

步骤

控制器是一个类,控制器的实例其实是IControllerActivator来创建的;

1.指定控制器的实例由容器来创建

2.注册控制器抽象和具体的关系

3.在控制器内定义属性

4.扩展,自己控制哪些属性需要做依赖注入(默认是让控制器中的属性都依赖注入)

 

 

实践

项目结构

在上节Autofac的整合到WebAPI的项目上改造。

 

 

 

指定控制器的实例由容器来创建

修改StartupConfigureServices方法。

services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());

 

 

 

注册控制器抽象和具体的关系

Startup的一个ConfigureContainer方法。

 

代码如下:

builder.RegisterType<TestServiceA>().As<ITestServiceA>().PropertiesAutowired();

            #region 注册所有控制器的关系+控制器实例化需要的所有组件

            Type[] controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()

             .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();

 

            builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired(new CustomPropertySelector());

            #endregion

 

 

在控制器内定义属性

修改WeatherForecastController控制器,代码如下:

[ApiController]

    [Route("[controller]")]

    public class WeatherForecastController : ControllerBase

    {

        [CustomPropertyAttribute]

        private ITestServiceA ServiceA { get; set; }

        private static readonly string[] Summaries = new[]

        {

            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"

        };

 

        private readonly ILogger<WeatherForecastController> _logger;

 

        public WeatherForecastController(ILogger<WeatherForecastController> logger)

        {

            _logger = logger;

          }

 

        [HttpGet]

        public IEnumerable<WeatherForecast> Get()

        {

            ServiceA.Show();

            var rng = new Random();

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast

            {

                Date = DateTime.Now.AddDays(index),

                TemperatureC = rng.Next(-20, 55),

                Summary = Summaries[rng.Next(Summaries.Length)]

            })

            .ToArray();

        }

    }

}

 

 

添加特性

代码如下:

 

[AttributeUsage(AttributeTargets.Property)]

    public class CustomPropertyAttribute : Attribute

    {

    }

 

 

public class CustomPropertySelector : IPropertySelector

    {

        public bool InjectProperty(PropertyInfo propertyInfo, object instance)

        {

            //需要一个判断的维度;

            return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(CustomPropertyAttribute));

        }

    }

 

运行

运行程序,结果如下。

 

 

 

 

 

 

总结

通过属性注入可以省去了在控制器中添加构造函数的参数。

posted @ 2022-05-20 22:57  春光牛牛  阅读(856)  评论(0编辑  收藏  举报