asp.net Core Autofac IOC 属性注入

asp.net Core 本事是提供IOC 但是没有属性注入都是构造函数注入,在网上看了一些文章都说属性注入慎用,会造成依赖关系的隐藏。那么接下来就是添加属性注入流程

第一步

NuGet程序包查询Autofac.Extensions.DependencyInjection 安装

第二步

找到根目录下Program 文件注入Autofac

代码

UseServiceProviderFactory(new Autofac.Extensions.DependencyInjection.AutofacServiceProviderFactory());

第三步

找到根目录下的Startup文件

代码

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

第四步

添加ConfigureContainer方法,这个会自动调用的

添加测试接口和实现类

我用到的是分区注入所以用到了类当然怎么注入接口和类看你自己

InstancePerLifetimeScope同等于asp.net Mvc 里面的InstancePerRequest 每个请求一个实例

代码

public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule<AutofacAttributeModel>();
}

public class AutofacAttributeModel : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AutofacTest>().As<IAutofacTest>().PropertiesAutowired().InstancePerLifetimeScope();
builder.RegisterType<AutofacService>().As<IAutofacService>().PropertiesAutowired().InstancePerLifetimeScope();

var controllerBaseType = typeof(ControllerBase);
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired(new AutowiredPropertySelector());
}
}

public class AutowiredPropertySelector : Autofac.Core.IPropertySelector
{
public bool InjectProperty(PropertyInfo propertyInfo, object instance)
{
return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(AutowiredAttribute));
}
}

[AttributeUsage(AttributeTargets.Property)]
public class AutowiredAttribute : Attribute
{
}

第五步

控制器添加属性注入

代码

[Startup.Autowired]
public IAutofacTest AutofacTest
{
get;
set;
}

结尾

参考文章

ASP.NET Core 奇淫技巧之伪属性注入 - 晓晨Master - 博客园

原文地址:https://www.cnblogs.com/changeMe/p/14452402.html