IOC:英文全称:Inversion of Control,中文名称:控制反转,它还有个名字叫依赖注入(Dependency Injection)。
作用:将各层的对象以松耦合的方式组织在一起,解耦,各层对象的调用完全面向接口。当系统重构的时候,代码的改写量将大大减少。
依赖注入: 当一个类的实例需要另一个类的实例协助时,在传统的程序设计过程中,通常有调用者来创建被调用者的实例。然而采用依赖注入的方式,创建被调用者的工作不再由调用者来完成,因此叫控制反转,创建被调用者的实例的工作由IOC容器来完成,然后注入调用者,因此也称为依赖注入。
Unity是微软Patterns & Practices团队所开发的一个轻量级的,并且可扩展的依赖注入(Dependency Injection)容器;
它支持常用的三种依赖注入方式:构造器注入(Constructor Injection)、属性注入(Property Injection),以及方法调用注入(Method Call Injection)。
现在Unity最新的版本的4.0版,可以在微软的开源站点 github.com/unitycontai… 下载最新的发布版本。
通过使用Unity,我们能轻松构建松耦合结构的程序,从而让整个程序框架变得清晰和易于维护。
ASP.NET Core 6.0 使用ServiceCollection
在Program中
builder.Services.AddTransient<类, 接口>();
在控制器中使用(有构造函数使用):
private readonly IClass1 class1;
private readonly IClass1 class2;
public 控制器名(IClass1 b,IServiceProvider c)
{
class1 = c.GetService<IClass1>();
class1 = b;
}
两种方法都一样,都需要在Program中注入,才能使用
Autofac支持ASP.NET Core 6.0 1、添加添加Autofac包 Autofac.Extensions.DependencyInjection包
2、在Program中
//添加Autofac包 Autofac.Extensions.DependencyInjection包 using Autofac.Extensions.DependencyInjection;
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
//using Autofac;
builder.Host.ConfigureContainer<ContainerBuilder>(a =>
{
a.RegisterType<Microphone(类名)>().As<IMicrophone(接口)>();
a.RegisterType<类名>().As<接口>();
});
属性注入
//添加Autofac包 Autofac.Extensions.DependencyInjection包 using Autofac.Extensions.DependencyInjection;
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
//using Autofac;
builder.Host.ConfigureContainer<ContainerBuilder>(a =>
{
a.RegisterType<Class1>().As<IClass>();
a.RegisterType<Class2>().As<IClass1>().EnableClassInterceptors();//using Autofac.Extras.DynamicProxy 支持AOP扩展
a.RegisterType<mo>();
var controllerBaseType = typeof(ControllerBase);
//注册一个程序集typeof(Program).Assembly当前所在的程序集
a.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired(); //支持属性注入
});
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
3、在控制器中写构造函数:
private IMicrophone _IMicrophone;
private IPhone _IPhone;
IEnumerable<IMicrophone> _IMicrophonelist;
[CusotmSelectAttribute]
public IMicrophone _IMicrophoneProp { get; set; }
public IMicrophone _IMicrophoneProp1 { get; set; }
public SixthController(IMicrophone microphone, IPhone phone, IEnumerable<IMicrophone> list, IServiceProvider serviceProvider, IComponentContext componentContext)
{
this._IMicrophone = microphone;
this._IPhone = phone;
this._IMicrophonelist = list;
IMicrophone microphone1 = serviceProvider.GetService<IMicrophone>();
IMicrophone microphone2 = componentContext.Resolve<IMicrophone>();
}