实用技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 实用技巧 > .NET Core使用Autofac容器

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

作者:Run2948

本文详细讲解了.NET Core使用Autofac容器的DI依赖注入,IOC控制反转及AOP切面编程,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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

您可能感兴趣的文章:
阅读全文