<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
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切面程式設計的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45