.NET Core中怎么使用Autofac

发布时间:2022-02-17 13:48:03 作者:iii
来源:亿速云 阅读:196

今天小编给大家分享一下.NET Core中怎么使用Autofac的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

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”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

推荐阅读:
  1. 如何使用.NET CORE HttpClient
  2. .Net Core如何使用MongoDB

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

core autofac

上一篇:Linux中如何使用tty命令

下一篇:Linux中如何使用true命令

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》