目录Autofac 容器Autofac 多种注入方式Autofac 生命周期Autofac 支持配置文件Autofac 整合 .net 5 mvcAutofac 支持控制器属性注入A
Autofac 是一款.NET ioc 容器 . 它管理类之间的依赖关系, 从而使 应用在规模及复杂性增长的情况下依然可以轻易地修改 . 它的实现方式是将常规的.net类当做组件
处理.
Autofac 6.0.0
ITestServiceA
和 TestServiceA
public interface ITestServiceA
{
void Show();
}
public class TestServiceA : ITestServiceA
{
public TestServiceA()
{
Console.WriteLine($"{this.GetType().Name} 被构造了...");
}
public void Show()
{
Console.WriteLine($"This is a {this.GetType().Name} Instance...");
}
}
Main
方法 var builder = new ContainerBuilder();
builder.ReGISterType<TestServiceA>().As<ITestServiceA>();
var container = builder.Build();
// 获取服务实例
var testService = container.Resolve<ITestServiceA>();
testService.Show();
ITestServiceB
和 TestServiceB
public interface ITestServiceB
{
void Show();
}
public class TestServiceB : ITestServiceB
{
private ITestServiceA _testServiceA;
public void SetService(ITestServiceA testServiceA)
{
_testServiceA = testServiceA;
}
public TestServiceB()
{
Console.WriteLine($"{this.GetType().Name} 被构造了...");
}
public void Show()
{
// _testServiceA.Show();
Console.WriteLine($"This is a {this.GetType().Name} Instance...");
}
}
ITestServiceC
和 TestServiceC
public interface ITestServiceC
{
void Show();
}
public class TestServiceC : ITestServiceC
{
public TestServiceC()
{
Console.WriteLine($"{this.GetType().Name} 被构造了...");
}
public void Show()
{
Console.WriteLine($"This is a {this.GetType().Name} Instance...");
}
}
ITestServiceD
和 TestServiceD
public interface ITestServiceD
{
void Show();
}
public class TestServiceD : ITestServiceD
{
public ITestServiceA TestServiceA { get; set; }
public ITestServiceB TestServiceB { get; set; }
public ITestServiceC TestServiceC { get; set; }
public TestServiceD()
{
Console.WriteLine($"{this.GetType().Name} 被构造了...");
}
public void Show()
{
// TestServiceA.Show();
// TestServiceB.Show();
// TestServiceC.Show();
Console.WriteLine($"This is a {this.GetType().Name} Instance...");
}
}
var builder = new ContainerBuilder();
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceB>().As<ITestServiceB>();
builder.RegisterType<TestServiceC>().As<ITestServiceC>();
builder.RegisterType<TestServiceD>().As<ITestServiceD>();
var container = builder.Build();
// 获取服务实例
var testService = container.Resolve<ITestServiceA>();
testService.Show();
var builder = new ContainerBuilder();
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceB>().As<ITestServiceB>();
builder.RegisterType<TestServiceC>().As<ITestServiceC>();
builder.RegisterType<TestServiceD>().As<ITestServiceD>().PropertiesAutowired();
var container = builder.Build();
// 获取服务实例
var testService = container.Resolve<ITestServiceD>();
testService.Show();
var builder = new ContainerBuilder();
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceB>().OnActivated(e =>
e.Instance.SetService(e.Context.Resolve<ITestServiceA>())
).As<ITestServiceB>();
builder.RegisterType<TestServiceC>().As<ITestServiceC>();
builder.RegisterType<TestServiceD>().As<ITestServiceD>();
var container = builder.Build();
// 获取服务实例
var testService = container.Resolve<ITestServiceB>();
testService.Show();
var builder = new ContainerBuilder();
builder.RegisterType<TestServiceA>().As<ITestServiceA>().InstancePerDependency();
var container = builder.Build();
var testServiceA = container.Resolve<ITestServiceA>();
var testServiceA1 = container.Resolve<ITestServiceA>();
Console.WriteLine(object.ReferenceEquals(testServiceA,testServiceA1));
var builder = new ContainerBuilder();
builder.RegisterType<TestServiceA>().As<ITestServiceA>().SingleInstance();
var container = builder.Build();
var testServiceA = container.Resolve<ITestServiceA>();
var testServiceA1 = container.Resolve<ITestServiceA>();
Console.WriteLine(object.ReferenceEquals(testServiceA,testServiceA1));
var builder = new ContainerBuilder();
builder.RegisterType<TestServiceA>().As<ITestServiceA>().InstancePerLifetimeScope();
var container = builder.Build();
ITestServiceA testServiceA15;
ITestServiceA testServiceA16;
using (var scope1 = container.BeginLifetimeScope())
{
var testServiceA11 = scope1.Resolve<ITestServiceA>();
var testServiceA12 = scope1.Resolve<ITestServiceA>();
Console.WriteLine(object.ReferenceEquals(testServiceA11,testServiceA12));
testServiceA15 = testServiceA12;
}
using (var scope1 = container.BeginLifetimeScope())
{
var testServiceA13 = scope1.Resolve<ITestServiceA>();
var testServiceA14 = scope1.Resolve<ITestServiceA>();
Console.WriteLine(object.ReferenceEquals(testServiceA13,testServiceA14));
testServiceA16 = testServiceA14;
}
Console.WriteLine(object.ReferenceEquals(testServiceA15,testServiceA16));
var builder = new ContainerBuilder();
builder.RegisterType<TestServiceA>().As<ITestServiceA>()
.InstancePerMatchingLifetimeScope("Run2948");
var container = builder.Build();
ITestServiceA testServiceA15;
ITestServiceA testServiceA16;
using (var scope1 = container.BeginLifetimeScope("Run2948"))
{
var testServiceA11 = scope1.Resolve<ITestServiceA>();
using (var scope2 = container.BeginLifetimeScope())
{
var testServiceA12 = scope2.Resolve<ITestServiceA>();
Console.WriteLine(object.ReferenceEquals(testServiceA11,testServiceA12));
}
testServiceA15 = testServiceA11;
}
using (var scope1 = container.BeginLifetimeScope("Run2948"))
{
var testServiceA13 = scope1.Resolve<ITestServiceA>();
using (var scope2 = container.BeginLifetimeScope())
{
var testServiceA14 = scope2.Resolve<ITestServiceA>();
Console.WriteLine(object.ReferenceEquals(testServiceA13,testServiceA14));
}
testServiceA16 = testServiceA13;
}
Console.WriteLine(object.ReferenceEquals(testServiceA15,testServiceA16));
InstancePerOwned : 在一个所拥有的实例创建的生命周期中,每次调用,都会使用同一个实例化的对象;每次都用同一个对象;(较少使用)
InstancePerHttpRequest : 同一次Http请求上下文中,每次调用,都会使用同一个实例化的对象;每次都用同一个对象;仅适用于 asp.net (CORE) MVC 或 WEBFORM 应用程序
Autofac.Extensions.DependencyInjection 7.1.0
、Autofac.Configuration 6.0.0
autofac.JSON
:{
"components":[
{
"type: "One.Services.TestServiceA,One",
"services": [
{
"type": "One.Services.ITestServiceA,One"
}
],
"instanceScope": "single-instance",
"injectProperties": true
},
{
"type: "One.Services.TestServiceB,One",
"services": [
{
"type": "One.Services.ITestServiceB,One"
}
],
"instanceScope": "single-instance",
"injectProperties": true
},
{
"type: "One.Services.TestServiceC,One",
"services": [
{
"type": "One.Services.ITestServiceC,One"
}
],
"instanceScope": "single-instance",
"injectProperties": true
},
{
"type: "One.Services.TestServiceD,One",
"services": [
{
"type": "One.Services.ITestServiceD,One"
}
],
"instanceScope": "single-instance",
"injectProperties": true
}
]
}
var builder = new ContainerBuilder();
var config = new ConfigurationBuilder();
var configSource = new jsonConfigurationSource()
{
Path = "Config/autofac.json",
Optional = false,
ReloadOnChange = true
};
config.Add(configSource);
var configModule = new ConfigurationModule(config.Build());
builder.RegisterModule(configModule);
var container = builder.Build();
// 获取服务实例
var testServiceA = container.Resolve<ITestServiceA>();
var testServiceD = container.Resolve<ITestServiceD>();
testServiceD.Show();
TestServiceUpdate
public class TestServiceUpdate : ITestServiceA
{
public TestServiceUpdate()
{
Console.WriteLine($"{this.GetType().Name} 被构造了...");
}
public void Show()
{
Console.WriteLine($"This is a {this.GetType().Name} Instance...");
}
}
autofac.json
来实现快速实现 ITestServiceA 的实现的重新定义:{
"components":[
{
"type: "One.Services.TestServiceUpdate,One",
"services": [
{
"type": "One.Services.ITestServiceA,One"
}
],
"instanceScope": "single-instance",
"injectProperties": true
},
// ...
安装 NuGet 程序包: Autofac.Extensions.DependencyInjection 7.1.0
Program文件中指定 Autofac 工厂替换默认工厂:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseServiceProviderFactory(new AutofacServiceProviderFactory());
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ITestServiceA _serviceA;
public ValuesController(ITestServiceA serviceA
{
_serviceA = serviceA;
}
[HttpGet]
public IActionResult Get()
{
_serviceA.Show();
return Ok();
}
}
public void ConfigureServices(IServiceCollection services)
{
#region IServiceCollection 注册的服务,将来也会交给 Autofac 处理
services.AddTransient<ITestServiceA, TestServiceA>();
services.AddTransient<ITestServiceB, TestServiceB>();
services.AddTransient<ITestServiceC, TestServiceC>();
#endregion
}
public void ConfigureContainer(ContainerBuilder builder)
{
// builder.RegisterType<TestServiceA>().As<ITestServiceA>();
// builder.RegisterType<TestServiceB>().As<ITestServiceB>();
// builder.RegisterType<TestServiceC>().As<ITestServiceC>();
builder.RegisterType<TestServiceD>().As<ITestServiceD>();
}
控制器本身是一个类,它的实例其实是有 IControllerActivator 来创建的。
public void ConfigureServices(IServiceCollection services)
{
// ...
#region 指定控制器的实例由容器来创建
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
#endregion
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<TestServiceA>().As<ITestServiceA>().PropertiesAutowired();
builder.RegisterType<TestServiceB>().As<ITestServiceB>();
#region 注册所有控制器的关系及控制器实例化所需要的组件
var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly)
.PropertiesAutowired();
#endregion
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
public ITestServiceA TestServiceA { get; set; }
public ITestServiceB TestServiceB { get; set; }
[HttpGet]
public IActionResult Get()
{
TestServiceA.Show();
TestServiceB.Show();
return Ok();
}
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class AutowaredAttribute : Attribute { }
public class PropertySelector : IPropertySelector
{
public bool InjectProperty(PropertyInfo propertyInfo, object instance)
{
return propertyInfo.CustomAttributes.Any(ca => ca.AttributeType == typeof(AutowaredAttribute));
}
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceB>().As<ITestServiceB>();
#region 注册所有控制器的关系及控制器实例化所需要的组件
var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly)
.PropertiesAutowired(new PropertySelector());
#endregion
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[Autowared]
public ITestServiceA TestServiceA { get; set; }
public ITestServiceB TestServiceB { get; set; }
[HttpGet]
public IActionResult Get()
{
TestServiceA.Show();
TestServiceB.Show();
return Ok();
}
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceUpdate>().As<ITestServiceA>();
}
private readonly IEnumerable<ITestServiceA> _testServiceAs;
public ValuesController(IEnumerable<ITestServiceA> testServiceAs)
{
_testServiceAs = testServiceAs;
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceUpdate>().As<ITestServiceA>();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource(type => type.IsAssignableTo<ITestServiceA>()));
}
private readonly TestServiceA _testServiceA;
private readonly TestServiceUpdate _testServiceUpdate;
public ValuesController(TestServiceA testServiceA,TestServiceUpdate testServiceUpdate)
{
_testServiceA = testServiceA;
_testServiceUpdate = testServiceUpdate;
}
public class AutofacModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
// base.Load(builder);
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceUpdate>().As<ITestServiceA>();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource(type => type.IsAssignableTo<ITestServiceA>()));
}
}
public void ConfigureContainer(ContainerBuilder builder)
{
// builder.RegisterModule(new AutofacModule());
builder.RegisterModule<AutofacModule>();
}
AOP 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。Autofac 的AOP是通过 Castle(也是一个容器)项目的名为 Autofac.Extras.DynamicProxy 核心部分实现的,顾名思义其实现方式为动态代理。
安装 NuGet 程序包: Castle.Core 4.4.1
、Autofac.Extras.DynamicProxy 6.0.0
新建自定义 AOP 拦截器
public class CustomAutofacAop : IInterceptor
{
public void Intercept(IInvocation invocation)
{
{
Console.WriteLine("方法执行前...");
}
invocation.Proceed();
{
Console.WriteLine("方法执行后...");
}
}
}
[Intercept(typeof(CustomAutofacAop))]
public interface ITestServiceA
{
void Show();
}
public void ConfigureContainer(ContainerBuilder builder)
{
//builder.RegisterType<CustomAutofacAop>();
builder.RegisterType(typeof(CustomAutofacAop));
builder.RegisterType<TestServiceA>().As<ITestServiceA>();
builder.RegisterType<TestServiceUpdate>().As<ITestServiceA>().EnableInterfaceInterceptors();
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly TestServiceA _testServiceA;
private readonly TestServiceUpdate _testServiceUpdate;
public ValuesController(TestServiceA testServiceA,TestServiceUpdate testServiceUpdate)
{
_testServiceA = testServiceA;
_testServiceUpdate = testServiceUpdate;
}
public IActionResult Get()
{
_testServiceA.Show();
_testServiceUpdate.Show();
return Ok();
}
}
到此这篇关于.net core使用Autofac容器的DI依赖注入,IOC控制反转及AOP切面编程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。
--结束END--
本文标题: .NET Core使用Autofac容器的DI依赖注入,IOC控制反转及AOP切面编程
本文链接: https://lsjlt.com/news/139518.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-05-21
2023-05-21
2023-05-21
2023-05-21
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0