文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

.NET Core使用Autofac容器的DI依赖注入,IOC控制反转及AOP切面编程

2024-04-02 19:55

关注

Autofac 容器

Autofac 是一款.NET IoC 容器 . 它管理类之间的依赖关系, 从而使 应用在规模及复杂性增长的情况下依然可以轻易地修改 . 它的实现方式是将常规的.net类当做组件处理.

	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...");
        }
    }
 var builder = new ContainerBuilder();
 builder.RegisterType<TestServiceA>().As<ITestServiceA>();
 var container = builder.Build();

 // 获取服务实例
 var testService = container.Resolve<ITestServiceA>();
 testService.Show();

Autofac 多种注入方式

    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...");
        }
    }
    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...");
        }
    }
    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();

Autofac 生命周期

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));

Autofac 支持配置文件

{
 	"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();
public class TestServiceUpdate : ITestServiceA
{
    public TestServiceUpdate()
    {
        Console.WriteLine($"{this.GetType().Name} 被构造了...");
    }

    public void Show()
    {
        Console.WriteLine($"This is a {this.GetType().Name} Instance...");
    }
}
{
 	"components":[
        {
            "type: "One.Services.TestServiceUpdate,One",
            "services": [
            	{
            		"type": "One.Services.ITestServiceA,One"
        		}
            ],
    		"instanceScope": "single-instance",
    		"injectProperties": true
        },
		// ...

Autofac 整合 .NET 5 MVC

    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>();
    }

Autofac 支持控制器属性注入

控制器本身是一个类,它的实例其实是有 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();
        }
    }

Autofac 单实例多实现

 	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>();
    }

Autofac 支持 AOP

AOP 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。Autofac 的AOP是通过 Castle(也是一个容器)项目的名为 Autofac.Extras.DynamicProxy 核心部分实现的,顾名思义其实现方式为动态代理。

 	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切面编程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯